﻿#coding:utf-8
import calendar
import codecs

from django.http import JsonResponse,HttpResponse
from django.views.decorators.csrf import csrf_exempt
from rest_framework.decorators import authentication_classes
import os
import pandas as pd
import xlwt
from io import BytesIO
from django.forms.models import model_to_dict
import datetime
import time
from OnlineJudge.utils import PublicMethods as pub
from django.db import connection  # django封装好的方法
from django.utils import timezone
import random
from OnlineJudge import models
from django.contrib.auth.hashers import make_password, check_password #引用djago自带的加密解密
from OnlineJudge.models import *
import redis as rs,time,json
from django.db.models import Q #导入Q查询
import re #正则分割字符串
import decimal
# Create your views here.
from OnlineJudge.models import *
from OnlineJudge.models import Solution as so
# from Online_Judge import images
from Online_Judge import settings
from xml.dom.minidom import parse
import xml.dom.minidom
import xml.etree.cElementTree as ET
#import xml.etree.ElementTree as ET  # 迭代生成xml
import xml.dom.minidom as MD  # 输出
from  xml.dom import  minidom
from datetime import datetime as dtime
from OnlineJudge.utils.PublicMethods import *   #导入公共方法
from django.core.cache import cache

#全局配置redis
redis = rs.Redis(password=config.REDISP_PASS)



#登录方法实现
def login(request):
    if request.method == 'POST':
        username = request.POST.get('username')
        password = request.POST.get('password')
        code = request.POST.get('code')
        user_data = Users.objects.filter(user_id=username).first()
        if user_data:
            if username and password and code:
                if username == user_data.user_id and (checkPassword(password,user_data.password) or md5CheckPassword(password,user_data.password)) and check_capture(request,code):
                    ip = get_ip(request)
                    time = datetime.datetime.now()
                    Loginlog.objects.create(user_id = username,password = 'no save',ip = ip,time = time)
                    token = create_token({'username':user_data.user_id})
                    massage = {"err": "login successful",'token':token}

                elif not check_capture(request, code):
                    massage = {"err": "verification code error"}
                elif not checkPassword(password,user_data.password) or not md5CheckPassword(password,user_data.password):
                    massage = {"err": "user and password do not match"}
            else:
                massage = {"err": "login information is incomplete"}
        else:
            massage = {"err": "no such user"}
        return JsonResponse(massage)
    if request.method == 'GET':
        res = pub.capture(request)
        return JsonResponse(res)

#判断密码是否相同
def checktowPassword(request):
    if request.method == 'GET':
        status = {'err':'API not found'}
        return JsonResponse(status)
    else:
        status = {}
        username = request.POST.get('username')
        password = request.POST.get('password')
        md5 = hashlib.md5() # 2，实例化md5() 方法
        md5.update(password.encode())  # 3，对字符串的字节类型加密
        pwd = md5.hexdigest() # 4，加密
        user_data = Users.objects.filter(user_id=username).first()
        if user_data:
            if username == user_data.user_id and (checkPassword(pwd, user_data.password) or md5CheckPassword(pwd, user_data.password)):
                status = {'err':True}
            else:
                status = {'err': False}
        else:
            status = {'err': False}
        return JsonResponse(status)


#注册方法实现
def register(request):
    if request.method == 'GET':
        res = pub.capture(request)
        return JsonResponse(res)
    else:
        #拿到前台的数据
        username = request.POST.get('name','')
        password = request.POST.get('pass','')
        nickname = request.POST.get('nickname','')
        checkPass = request.POST.get('checkPass','')
        school = request.POST.get('school','')
        email = request.POST.get('email','')
        realname = request.POST.get('realname','')
        code = request.POST.get('code')
        data = Users.objects.filter(email=email).first()
        user_exist = Users.objects.filter(user_id=username).first()
        if data:
            state = {"err": "Email has been registered!"}
            return JsonResponse(state)
        if user_exist:
            state = {"err": "User name exists！"}
            return JsonResponse(state)
        if not pub.check_capture(request,code):
            state = {"err": "Verification code error!"}
            return JsonResponse(state)
        elif not pub.checkRegester(username,password,checkPass,nickname,email,school):
            state = {"err": "data formatting error!"}
            return JsonResponse(state)
        else:
            ip = get_ip(request)
            redis.setex(ip+'email',600,email)
            user_info = {"username":username,"password":password,"nickname":nickname,"school":school,"realname":realname}
            redis.setex(email+'_check',600,str(user_info))
            state = {"err":'True'}
            return JsonResponse(state)

#验证邮箱验证码 并将数据写入数据库
def check_email(request):
    email = request.POST.get('email')
    code = request.POST.get('email_capture')
    use_info = redis.get(email+'_check')
    print(use_info)
    if use_info:
        a = use_info.decode('utf-8', 'ignore').replace('\'', '"')
        use_info = json.loads(a)
        if pub.check_email_code(email,code):
            obj = Users.objects.create(user_id=use_info['username'],
                                              email=email,
                                              reg_time=time.strftime("%Y-%m-%d %H:%M:%S",time.localtime(time.time())),
                                              nick=use_info['nickname'],
                                              school=use_info['school'],
                                              real_name=use_info['realname'],
                                              ip=pub.get_ip(request),
                                              volume=1,
                                              language=1,
                                              score=0,
                                              submit=0,
                                              solved=0,
                                              defunct='N',
                                              password=pub.reg_pass(use_info['password']))
            if obj:
                state = {"err": 'True'}
                return JsonResponse(state)
        else:
            state = {"err": 'Verification code error'}
            return JsonResponse(state)
    else:
        state = {"err": 'The user does not exist.'}
        return JsonResponse(state)

#发送邮箱验证码
def sendEmail(request):

    if request.method== 'POST':
        email = request.POST.get('email')
        content = request.POST.get('content','注册用户')
        if not redis.get(email+'_check') is None:
              if pub.send_email(email,content):
                  state = {"err": 'Send True'}
                  return JsonResponse(state)
              else:
                  state = {"err": 'Send False'}
                  return JsonResponse(state)
        else:
            state = {"err": 'Send False'}
            return JsonResponse(state)
    else:
        ip=get_ip(request)
        email=redis.get(ip+'email')
        info = {}
        info['email']=email

        return JsonResponse(info,safe=False)

#首页显示前十竞赛信息
def index(request):
    data = {}
    #近期六条竞赛

    try:
        contests =cache.__getattr__("contests")
        contestList = []
        for contest in contests:
            if judgeContest(contest.contest_id):
                massage = 'true'
            else:
                massage = 'false'
            contestList.append(
                {
                    'massage': massage,
                    'contest_id': contest.contest_id,
                    'start_time': contest.start_time,
                    'end_time': contest.end_time,
                    'title': contest.title,
                    'creator': contest.creator,
                    'private': contest.private

                }
            )
        data["contests"] = contestList
    except:
        contests =' '
        data["contests"] = contests
    #data["contests"] = contestList
    try:
        # 近期十条新闻
        newsList = cache.__getattr__("newsList")
        data["news"] = newsList
        data["news"] = changeToJson(newsList)
    except:
        newsList = " ";
        data["news"]=newsList;

    try:
        # #近期做题排名
        day_rank =cache.__getattr__("day_rank") #每日排名
        data["day_rank"] = day_rank
    except:
        day_rank = ' ';
        data["day_rank"]=day_rank;
    try:
        week_rank = cache.__getattr__("week_rank") #每周排名
        data['week_rank'] = week_rank
    except:
        week_rank = " "  # 每周排名
        data['week_rank'] = week_rank
    try:
        month_rank = cache.__getattr__("month_rank") #每月排名
        data['month_rank'] = month_rank
    except:
        month_rank = ' '  # 每月排名
        data['month_rank'] = month_rank
    # 数据统计
    data_statistics = []
    problem_count = " "
    submit_count = " "
    Users_count = " "
    day_subimt_count = " "
    try:
        problem_count = cache.__getattr__("problem_count")
        submit_count =cache.__getattr__("submit_count")
        Users_count =cache.__getattr__("users_count")
        day_subimt_count = cache.__getattr__("day_subimt_count")

    except:
        problem_count = " "
        submit_count = " "
        Users_count = " "

        day_subimt_count = " "
    data_statistics.append(
        {
            'problem_count' : problem_count,
            'submit_count': submit_count,
            'Users_count': Users_count,
            'day_subimt_count': day_subimt_count,

        }
    )
    data["data_statistics"] = data_statistics

    month = ['一月大','二月小','三月大','四月小','五月大','六月小','七月大','八月大','九月小','十月大','十一月小','十二月大']
    week = ['星期一','星期二','星期三','星期四','星期五','星期六','星期日']
    sentence = ['当你手中抓住一件东西不放时，你只能拥有一件东西，如果你肯放手，你就有机会选择更多。与其在别人的生活里跑龙套，不如精彩做自己。','没有特别幸运，那么请先特别努力，别因为懒惰而失败，还矫情地将原因归于自己倒霉。你必须特别努力，才能显得毫不费力。','你的时间有限，不要浪费于重复别人的生活。不要让别人的观点淹没了你内心的声音。——乔布斯','人生在世，总有顺利或不顺利，得意或不得意的时候，但是最好坚持下去。一个不稳重的人，做什么都很难取得成功。','人无所舍，必无所成。跌倒了，失去了，不要紧，爬起来继续风雨兼程，且歌且行。','努力做一个积极的人。不埋怨谁，不嘲笑谁，也不羡慕谁，阳光下灿烂，风雨中奔跑，做自己的梦，走自己的路。','上天不会亏待努力的人，也不会同情假勤奋的人，你有多努力，时光它知道。']
    nowMonth = datetime.datetime.now().month
    nowWeek = datetime.datetime.now().weekday()
    data['nowWeek'] = week[nowWeek]
    data['nowMonth'] = month[nowMonth-1]
    data['nowDay'] = '%02d' % datetime.datetime.now().day
    data['sentence'] = sentence[nowWeek]
    return JsonResponse(data,safe=False)


#排行并分页
def userRank(request):
    if request.method == "GET":
        page = int(request.GET.get('page','1'))
        content = request.GET.get('content', '')
        time = request.GET.get('time','')
    now = datetime.datetime.now()
    cpage = (page - 1) * 50 + 1
    if time == '':
        users = Users.objects.filter(Q(user_id__contains=content) | Q(nick__contains=content)).all().order_by('-solved','user_id')[(page-1)*50:page*50]
        ten_users = Users.objects.filter(Q(user_id__contains=content) | Q(nick__contains=content)).all().order_by('-solved','user_id')[(page-1)*50:(page-1)*50+10]
        users_data = []
        ten_nick = []
        ten_solved = []
        ten_submit = []
        for data in ten_users:
            ten_nick.append(data.nick)
            ten_solved.append(data.solved)
            ten_submit.append(data.submit)
        for data in users:
            if data.submit == 0:
                ratio = '%s%%' % (format(0, '.2f'))
            else:
                ratio = data.solved/data.submit
                ratio = '%s%%' % (format(ratio*100, '.2f'))
            users_data.append(
                {
                    'rank':cpage,
                    'nick':data.nick,
                    'user_id':data.user_id,
                    'solved':data.solved,
                    'submit':data.submit,
                    'ratio': ratio
                }
            )
            cpage = cpage + 1
        total = Users.objects.filter(Q(user_id__contains=content) | Q(nick__contains=content)).all().count()
        rank = {'rank': users_data, 'page': page, 'total': total, 'ten_nick': ten_nick, 'ten_solved': ten_solved,'ten_submit': ten_submit}
        return JsonResponse(rank, safe=False)
    else:
        time = int(time)
        user_data = []
        users = []
        ten_users = []
        users1 = getRankListByTime(now - datetime.timedelta(days=time), (page - 1) * 50, page * 50)

        ten_users1 = getRankListByTime(now - datetime.timedelta(days=time), (page-1)*50, (page-1)*50+10)
        if content:
            for data in users1:
                if content in data[0]:
                    users.append(data)
            ten_users = users[:10]

        else:
            users = users1
            ten_users = ten_users1
        ten_nick = []
        ten_solved = []
        ten_submit = []
        for data in ten_users:
            ten_nick.append(data[1])
            ten_solved.append(data[2])
            ten_submit.append(data[3])
        for data in users:
            if data[3] == 0:
                ratio = '%s%%' % (format(0, '.2f'))
            else:
                ratio = data[2]/data[3]
                ratio = '%s%%' % (format(ratio*100, '.2f'))
            user_data.append(
                {
                    'rank': cpage,
                    'nick': data[1],
                    'user_id': data[0],
                    'solved': data[2],
                    'submit': data[3],
                    'ratio': ratio
                }
            )
            cpage = cpage + 1
        total = len(user_data)
        rank = {'rank': user_data, 'page': page, 'total': total, 'ten_nick': ten_nick, 'ten_solved': ten_solved,'ten_submit': ten_submit}
        return JsonResponse(rank, safe=False)

#按题目编号，难度，正确数，提交数排序,搜索，标签，来源
def problemList(request):
    page = int(request.GET.get('page', '1'))
    sort = request.GET.get('sort','problem_id')
    key = request.GET.get('content','')
    type = request.GET.get('type')
    source = request.GET.get('source')
    user_id = request.GET.get('user_id')
    if type:
        users = Problem.objects.only('accepted','difficulty','problem_id','solved','source','submit','title','type').filter(type = type,defunct='N').order_by(sort)[(page - 1) * 50:page * 50]
        total = Problem.objects.filter(type = type,defunct='N').count()
    elif source:
        users = Problem.objects.only('accepted','difficulty','problem_id','solved','source','submit','title','type').filter(source = source,defunct='N').order_by(sort)[(page - 1) * 50:page * 50]
        total = Problem.objects.filter(source = source,defunct='N').count()
    else:
        users = Problem.objects.filter(Q(problem_id__contains=key)|Q(title__contains=key),defunct='N').only('accepted','difficulty','problem_id','solved','source','submit','title','type').order_by(sort)[(page - 1) * 50:page * 50]
        total = Problem.objects.filter(Q(problem_id__contains=key)|Q(title__contains=key),defunct='N').count()

    rank_data = []
    for data in users:
        result =getSolutionResult(data.problem_id,user_id)
        if result == 'ture':
            result = 'ture'
        if result == 'falsh':
            result = 'falsh'
        if result == 'none':
            result = 'none'
        rank_data.append(
            {
                'accepted':data.accepted,
                'difficulty': data.difficulty,
                'problem_id': data.problem_id,
                'result': result,
                'solved': data.solved,
                'source': data.source,
                'submit': data.submit,
                'title': data.title,
                'type': data.type,
            }
        )



    problem_type = Problem.objects.filter(defunct='N').values("type")
    label = []
    for item in problem_type:
        if item['type'] is not None:
            label.append(item['type'])
    label = list(set(label))

    problem_source = Problem.objects.filter(defunct='N').values("source")
    source = []
    for item in problem_source:
        if item['source'] is not None:
            source.append(item['source'])
    source = list(set(source))
    rank = {'label':label,'source':source,'rank':rank_data,'total':total,'page':page}
    return JsonResponse(rank, safe=False)

#问题详情
def problem(request):
    problem_id = request.GET.get('problem_id')
    user_id = request.GET.get('user_id')
    if user_id:
        problem_collection = Collection.objects.filter(problem_id = problem_id,user_id = user_id).first()
        if problem_collection:
            massage = 'Ture'
        else:
            massage = 'False'
    else:
        massage = 'None'
    result =getSolutionResult(problem_id,user_id)
    if result == 'ture':
        result = 'ture'
    if result == 'falsh':
        result = 'falsh'
    if result == 'none':
        result = 'none'
    problem = Problem.objects.filter(problem_id = problem_id).all()
    problem = changeToJson(problem)
    statistics = [0, 0, 0, 0, 0, 0, 0, 0,0]
    for i in range(4,13):
        statistics[i-4] = Solution.objects.filter(problem_id = problem_id, result = i).count()
    rank = {'problem':problem,'statistics':statistics,'massage':massage,'result':result}
    return JsonResponse(rank, safe=False)

#题解列表
def titleSolution(request):
    if request.method == 'GET':
        pid = request.GET.get('pid')
        page = request.GET.get('page','1')
    if pid:
        problemSolution = Topic.objects.filter(pid=pid,defunct = 'N')[(int(page)-1)*30:int(page)*30]
        totle = Topic.objects.filter(pid=pid,defunct = 'N').count()
        problemSolution_data = []
        for data in problemSolution:
            problemSolution_data.append(
                {
                    'title':data.title.decode('utf-8'),
                    'content':data.content,
                    'time':data.time,
                    'author_id':data.author_id
                }
            )
        massage = {'problemSolution_data': problemSolution_data, 'totle': totle,}
        return JsonResponse(massage, safe=False)
    else:
        massage = {'massage':"You don't have access"}
        return JsonResponse(massage,safe = False)

#提交状态
def submissionState(request):
    if request.method == 'GET':
        page = int(request.GET.get('page', '1'))
        problem_id = request.GET.get('problem_id','')
    solution = Solution.objects.filter(problem_id = problem_id,defunct = 'N')[(page - 1) * 50:page * 50]
    solution = changeToJson(solution)
    statistics = [0, 0, 0, 0, 0, 0, 0, 0,0]
    for i in range(4,13):
        statistics[i-4] = Solution.objects.filter(problem_id = problem_id, result = i).count()
    result = {'solution': solution, 'page': page,'statistics': statistics}
    return JsonResponse(result,safe=False)

#我要写题解
def problemSolving(request):
    if request.method == 'POST':
        title = request.POST.get('title')
        time = datetime.datetime.now()
        defunct = request.POST.get('defunct', 'Y')
        content = request.POST.get('content')
        top_level = request.POST.get('top_level','0')
        cid = request.POST.get('cid', '')
        pid = request.POST.get('pid', '')
        author_id = request.POST.get('author_id', '')

        if title and content:
            title.replace("&nbsp;"," ")
            title.strip()
            content.replace("<p>", "")
            content.replace("</p>", "<br />")
            content.replace(",", "&#44;")
            content.replace("&nbsp;", " ")
            content.strip()
            Topic.objects.create(title=title, content=content, time=time, defunct=defunct, top_level=top_level, cid=cid,pid=pid, author_id=author_id)
            massage = {'err':'Saved successfully'}
        else:
            massage = {'err':'Incomplete information'}
        count = Solution.objects.filter(user_id=author_id).count()
        if count % 100 == 0:
            userinfo = Users.objects.get(user_id=author_id)
            userinfo.score += 100
        return JsonResponse(massage,safe=False)

#给题解点赞方法
def praise(request):
    if request.method == 'GET':
        user_id = request.GET.get('user_id')
        topic_id = request.GET.get('topic_id')
    if user_id and topic_id:
        topic = isPraised(user_id,topic_id)
        topic = topic[0]
        topic = ''.join(map(str, topic))
        print(topic)
        if topic == '0':
            Praise.objects.create(user_id = user_id , topic_id = topic_id)
            massage = {'err':'Like success'}
        else:
            Praise.objects.filter(user_id = user_id, topic_id = topic_id).delete()
            massage = {'err':'Click like to cancel'}
    else:
        massage = {'err': 'Page error'}
    return JsonResponse(massage, safe=False)



#状态页面
def status(request):
    if request.method == 'GET':
        problem_id = request.GET.get('problem_id','')
        user_id = request.GET.get('user_id','')
        language = int(request.GET.get('language','-1'))
        result = int(request.GET.get('result','-1'))
        page = int(request.GET.get('page','1'))

    statusData={}
    data,statusData['count'] = searchStatus(problem_id,user_id,language,result,page)
    statusData['data'] = changeToJson(data)
    for data in statusData['data']:
        sim = Sim.objects.filter(s_id=data['solution_id']).first()
        if sim and sim.sim >= 50:
            data['sim_id'] = sim.sim_s_id
        else:
            data['sim_id'] = 0
    return JsonResponse(statusData,safe=False)


#对比页面
def samecode(request):
    solution_id = request.POST.get('solution_id')
    sim_id = request.POST.get('sim_id')
    admin = request.POST.get('admin')
    if not (verifyPrivilege(admin)[0][0] == 1 or verifyPrivilege(admin)[0][0] == 0):
        massage = {'err': 'Insufficient authority'}
        return JsonResponse(massage, safe=False)
    source1 = []
    solution = Solution.objects.filter(solution_id=solution_id).first()
    if solution_id:
        code = SourceCode.objects.filter(solution_id=solution_id).first()
        code = code.source
        source1.append({
            'code': code,
            'User': solution.user_id,
            'Problem': solution.problem_id,
            'Language': solution.language,
            'Result': solution.result,
            'memory': solution.memory,
            'time': solution.time
        })
    source2 = []
    solution = Solution.objects.filter(solution_id=sim_id).first()
    if solution_id:
        code = SourceCode.objects.filter(solution_id=sim_id).first()
        code = code.source
        source2.append({
            'code': code,
            'User': solution.user_id,
            'Problem': solution.problem_id,
            'Language': solution.language,
            'Result': solution.result,
            'memory': solution.memory,
            'time': solution.time
        })
    massage = {'source1':source1,'source2':source2}
    return JsonResponse(massage, safe=False)


#查询个人信息
def getUsersInfo(request):
    if request.method == 'GET':
        user_id = request.GET.get('user_id')
    datas = Users.objects.filter(user_id=user_id)
    for data in datas:
        info = {
            'user_id': data.user_id,
            'regtime': data.reg_time,
            'school': data.school,
            'score': data.score,
            'nick': data.nick
        }

    return JsonResponse(info,safe=False)

#作业竞赛页面和我的竞赛
def contest(request):
    if request.method == 'GET':
        page = int(request.GET.get('page','1'))
        content = request.GET.get('content', '')
        user_id = request.GET.get('user_id', '')
    if user_id == '':
        try:
            content_num = int(content)
        except:
            content_num = content
        contest = Contest.objects.filter(Q(contest_id__contains=content_num) | Q(title__contains=content),defunct ='N').all().order_by('-contest_id')[(page-1)*50:page*50]
    else:
        contest = Privilege.objects.filter(user_id=user_id, defunct='N').values('rightstr')[(page-1)*50:page*50]

    contest_data = []
    for data in contest:
        if user_id == '':
            contest_id = data.contest_id
        else:
            data = data['rightstr']
            try:
                contest_id = data[1:]
                data = Contest.objects.filter(contest_id=contest_id).first()
            except:
                break
        endtime = Contest.objects.filter(contest_id=contest_id).values('end_time').first()
        endtime = endtime['end_time']
        endtime = datetime.datetime.strftime(endtime, '%Y-%m-%d %H:%M:%S')
        if judgeContest(contest_id):
            err = '@进行中{}'.format(endtime)
        else:
            err = '@已结束{}'.format(endtime)
        contest_data.append(
            {
                'contest_id':contest_id,
                'title':data.title,
                'time':err,
                'private':data.private,
                'creator':data.creator
            }
        )
    if user_id == '':
        total = Contest.objects.filter(Q(contest_id__contains=content_num) | Q(title__contains=content),defunct ='N').all().count()
    else:
        total = Privilege.objects.filter(user_id=user_id, defunct='N').count()
    result = {'contest': contest_data, 'page': page, 'total': total}
    return JsonResponse(result, safe=False)

#进入竞赛题目页面
def contestProblemList(request):
    if request.method == 'GET':
        contest_id = request.GET.get('contest_id')
        user_id = request.GET.get('user_id')
    private = Contest.objects.filter(contest_id=contest_id).all().values('private')
    private = private[0]
    private = private['private']
    contest = Contest.objects.filter(contest_id=contest_id).all()
    contest = changeToJson(contest)
    privilegelist = verifyPrivilege(user_id)
    contest_privilege = 'c' + contest_id
    if (private == 1 or private == 2) and verifyPrivilege(user_id)[0][0] != 1 and verifyPrivilege(user_id)[0][0] != 0 and contest_privilege not in privilegelist and not JudgmentAuthority(user_id,'contest_creator'):
        password = request.GET.get('password')
        if not password:
            massage = {'err':'Password error'}
            result = {'massage':massage,'contest':contest}
            return JsonResponse(result, safe=False)
        sr_password = Contest.objects.filter(contest_id=contest_id).all().values('password')
        sr_password = sr_password[0]
        sr_password = sr_password['password']
        if password == sr_password:
            problem_data = []
            problems = ContestProblem.objects.filter(contest_id=contest_id).order_by('num').values('problem_id')
            for problem in problems:
                problem = problem['problem_id']
                result = getContestSolutionResult(problem, user_id, contest_id)
                if result == 'ture':
                    result = 'ture'
                if result == 'falsh':
                    result = 'falsh'
                if result == 'none':
                    result = 'none'
                submit = 0
                solved = 0
                contests = Solution.objects.filter(problem_id=problem, contest_id=contest_id).all()
                num = ContestProblem.objects.filter(problem_id=problem, contest_id=contest_id).values('num')
                num = num[0]
                num = num['num']
                title = Problem.objects.filter(problem_id=problem).values('title')
                if title:
                    title = title[0]
                    title = title['title']
                    for data in contests:
                        if data.result == 4:
                            solved += 1
                        else:
                            submit += 1
                    problem_data.append(
                        {
                            'problem_id': problem,
                            'num': num,
                            'title': title,
                            'solved': solved,
                            'result':result,
                            'submit': submit + solved
                        }
                    )
            massage = {'err': 'Password ture'}
            result = {'contest': contest, 'problem': problem_data,'massage':massage}
            return JsonResponse(result, safe=False)
        else:
            massage = {'err':'Password error'}
            result = {'massage':massage,'contest':contest}
            return JsonResponse(result, safe=False)
    else:
        problem_data = []
        problems = ContestProblem.objects.filter(contest_id=contest_id).order_by('num').values('problem_id')
        for problem in problems:
            problem = problem['problem_id']
            result = getContestSolutionResult(problem, user_id, contest_id)
            if result == 'ture':
                result = 'ture'
            if result == 'falsh':
                result = 'falsh'
            if result == 'none':
                result = 'none'
            submit = 0
            solved = 0
            contests = Solution.objects.filter(problem_id=problem,contest_id = contest_id).all()
            num = ContestProblem.objects.filter(problem_id=problem, contest_id=contest_id).values('num')
            num = num[0]
            num = num['num']
            title = Problem.objects.filter(problem_id=problem).values('title')
            if title:
                title = title[0]
                title = title['title']
                for data in contests:
                    if data.result == 4:
                        solved += 1
                    else:
                        submit += 1
                problem_data.append(
                    {
                        'problem_id': problem,
                        'num':num,
                        'title':title,
                        'solved':solved,
                        'result':result,
                        'submit':submit+solved
                    }
                )
        result = {'contest': contest, 'problem': problem_data}
        return JsonResponse(result, safe=False)

#竞赛排名
def contestRankList(request):
    if request.method == 'GET':
        contest_id = request.GET.get('contest_id')
    starttime = Contest.objects.filter(contest_id=contest_id).values('start_time').first()
    starttime = starttime['start_time']
    users = getUsers(contest_id)
    nums = getNum(contest_id)
    contestRank = []
    num_time = []
    for num in nums:
        num = ''.join(map(str, num))
        num_data = getContestFirstRightNumSubmitTime(contest_id, num)
        if num_data:
            num_data = num_data['in_date']
            num_data = num_data - starttime
            num_data = timedeltaChange(num_data)
        else:
            num_data = '00:00:00'
        num_time.append(num_data)
    for user in users:
        user = ''.join(map(str, user))
        now = datetime.datetime.now()
        sumtime = now - now
        nick = Users.objects.filter(user_id=user).values('nick').first()
        nick = nick['nick']
        sumsolved = 0
        contestNum = []
        contesttime = []
        errcount = []
        sumerrcount = 0
        for num in nums:
            num = ''.join(map(str, num))
            time = getContestFirstRightSubmitTime(contest_id, user, num)
            errcount_data = getContestSubmitFalseCount(contest_id, user, num)
            sumerrcount = int(errcount_data) + sumerrcount
            errcount.append(errcount_data)
            if time:
                time = time['in_date']
                time = time-starttime
                sumsolved = sumsolved + 1
                rstime = timedeltaChange(time)
            else:
                timenow = datetime.datetime.now()
                time = timenow - timenow
                rstime = timedeltaChange(time)

            num = chr(int(num)+65)
            contestNum.append(num)
            contesttime.append(rstime)
            sumtime = sumtime + time
        sumtime = timedeltaChange(sumtime)
        contestRank.append(
            {
                'user': user,
                'contestNum': contestNum,
                'contesttime':contesttime,
                'nick': nick,
                'sumtime': sumtime,
                'sumsolved': sumsolved,
                'errcount': errcount,
                'sumerrcount':sumerrcount,
                'num_time':num_time
            }
        )
    contestRank = sorted(contestRank,key=lambda x:(-x["sumsolved"],x['sumtime'],-x['sumerrcount']))
    rs = [contestRank,num_time]
    return JsonResponse(rs,safe=False)

#oi竞赛排名
def contestRankList_oi(request):
    if request.method == 'GET':
        contest_id = request.GET.get('contest_id')
    starttime = Contest.objects.filter(contest_id=contest_id).values('start_time').first()
    starttime = starttime['start_time']
    users = getUsers(contest_id)
    nums = getNum(contest_id)
    contestRank = []
    num_time = []
    for num in nums:
        num = ''.join(map(str, num))
        num_data = getContestFirstRightNumSubmitTime(contest_id, num)
        if num_data:
            num_data = num_data['in_date']
            num_data = num_data - starttime
            num_data = timedeltaChange(num_data)
        else:
            num_data = '00:00:00'
        num_time.append(num_data)
    for user in users:
        user = ''.join(map(str, user))
        now = datetime.datetime.now()
        sumtime = now - now
        nick = Users.objects.filter(user_id=user).values('nick').first()
        nick = nick['nick']
        sumsolved = 0
        contestNum = []
        contesttime = []
        errcount = []
        sumerrcount = 0
        for num in nums:
            num = ''.join(map(str, num))
            time = getContestFirstRightSubmitTime(contest_id, user, num)
            errcount_data = getContestSubmitFalseCount(contest_id, user, num)
            sumerrcount = int(errcount_data) + sumerrcount
            errcount.append(errcount_data)
            if time:
                time = time['in_date']
                time = time-starttime
                sumsolved = sumsolved + 1
                rstime = timedeltaChange(time)
            else:
                timenow = datetime.datetime.now()
                time = timenow - timenow
                rstime = timedeltaChange(time)

            num = chr(int(num)+65)
            contestNum.append(num)
            contesttime.append(rstime)
            sumtime = sumtime + time
        sumtime = timedeltaChange(sumtime)
        contestRank.append(
            {
                'user': user,
                'contestNum': contestNum,
                'contesttime':contesttime,
                'nick': nick,
                'oi':sumsolved *100,
                'sumtime': sumtime,
                'sumsolved': sumsolved,
                'errcount': errcount,
                'sumerrcount':sumerrcount,
                'num_time':num_time
            }
        )
    contestRank = sorted(contestRank,key=lambda x:(-x["sumsolved"],x['sumtime'],-x['sumerrcount']))
    rs = [contestRank,num_time]
    return JsonResponse(rs,safe=False)


# 竞赛状态页面
def contestStatus(request):
    if request.method == 'GET':
        contest_id = request.GET.get('contest_id')
        num = request.GET.get('num', '')
        if num:
            num = ord(num) - 65
        user_id = request.GET.get('user_id', '')
        language = int(request.GET.get('language', '-1'))
        result = int(request.GET.get('result', '-1'))
        page = int(request.GET.get('page', '1'))
    statusData = {}
    data,statusData['count'] = contestSearchStatus(num, user_id, language, result, page, contest_id)
    statusData['data'] = changeToJson(data)
    for data in statusData['data']:
        data['pass_rate'] = str(round(data['pass_rate']*100,0))+'%'
        sim = Sim.objects.filter(s_id=data['solution_id']).first()
        if sim and sim.sim >= 50:
            data['sim_id'] = sim.sim_s_id
        else:
            data['sim_id'] = 0
    return JsonResponse(statusData, safe=False)

#竞赛统计
def contestStatistics(request):
    if request.method == 'GET':
        contest_id = request.GET.get('contest_id')
    nums = getNum(contest_id)
    problem_data = []
    for num in nums:
        num = ''.join(map(str, num))
        problem_id = ContestProblem.objects.filter(contest_id=contest_id, num = num).values('problem_id')
        problem_id = problem_id[0]
        problem_id = problem_id['problem_id']
        statistics = [0,0,0,0,0,0,0,0]
        problem_all = Solution.objects.filter(contest_id=contest_id, num = num).all()
        total = Solution.objects.filter(contest_id=contest_id, num=num).all().count()
        for data in problem_all:
            statistics[data.result - 4] += 1
        problem_data.append(
            {
                'problem_id':problem_id,
                'num':num,
                'statistics':statistics,
                'TR':'TR',
                'total':total
            }
        )
    return JsonResponse(problem_data, safe=False)

#发送站内信
def sendMail(request):
    if request.method == 'POST':
        to_user=request.POST.get('to_user')
        from_user = request.POST.get('from_user')
        title = request.POST.get('title')
        content = request.POST.get('content')
        in_date =time.strftime("%Y-%m-%d %H:%M:%S", time.localtime())
        mail = Mail.objects.create(
                            to_user=to_user,
                            from_user=from_user,
                            title=title,
                            content=content,
                            in_date=in_date,
                            new_mail=1,
                            reply=0,
                            defunct=1
        )
        if mail:
            asg = {"err": 'True'}
            return JsonResponse(asg)
        else:
            asg = {"err": 'False'}
            return JsonResponse(asg)


#取出站内信
def getMail(request):
    if request.method == 'GET':
        mail_id =request.GET.get('mail_id')
        to_user = request.GET.get('to_user')
        msg = Mail.objects.filter(mail_id=mail_id,to_user=to_user)
        msg = changeToJson(msg)
        if msg!='':
            return JsonResponse(msg, safe=False)
        else :
            state={
                'message':'null'
            }
            return JsonResponse(state, safe=False)


#站内信已读列表
def getMyMailList(request):

    if request.method == 'GET':
        to_user = request.GET.get('to_user')
        list = Mail.objects.filter(to_user=to_user,new_mail=1).all().order_by('mail_id')
        list = changeToJson(list)
        if list!='':
            return JsonResponse(list, safe=False)
        else :
            state={
                'message':'null'
            }
            return JsonResponse(state, safe=False)


#收到的所有站内信
def getAllMailList(request):
    if request.method=="GET":
        to_user = request.GET.get('to_user')
        paper = int(request.GET.get('paper', '1'))
        list = Mail.objects.filter(Q(to_user=to_user)&(Q(defunct__contains=1)| Q(defunct__contains=3))).all().order_by('mail_id')[20*(paper-1):paper*20]
        list = changeToJson(list)
        count = Mail.objects.filter(Q(to_user=to_user)&(Q(defunct__contains=1)| Q(defunct__contains=3))).count()
        total = {'total': count}
        lists = []
        lists.append(list)
        lists.append(total)
        if list != '':
            return JsonResponse(lists, safe=False)
        else:

            state = {
                'message': 'null'
            }
            return JsonResponse(state, safe=False)


#我发送的邮件列表
def mySendMail(request):
    if request.method=="GET":
        from_user = request.GET.get('from_user')
        paper = int(request.GET.get('paper','1'))
        list = Mail.objects.filter(Q(from_user=from_user)&(Q(defunct__contains=1)| Q(defunct__contains=2))).all().order_by('mail_id')[20*(paper-1):paper*20]
        list = changeToJson(list)

        count =  Mail.objects.filter(Q(from_user=from_user)&(Q(defunct__contains=1)| Q(defunct__contains=2))).count()
        total = {'total':count}
        lists=[]
        lists.append(list)
        lists.append(total)
        if list != '':
            return JsonResponse(lists, safe=False)
        else:
            state = {
                'message': 'null'
            }
            return JsonResponse(state, safe=False)

#站内信已读
def mailRead(request):
    if request.method =='POST':
        mail_id = request.POST.get('mail_id')
        mail = Mail.objects.get(mail_id=mail_id)
        mail.new_mail = 0
        mail.save()


#删除收到的站内信
def deleteMail(request):
    if request.method=='POST':
        mail_id =request.POST.get('mail_id')
        status = Mail.objects.get(mail_id=mail_id)
        status.defunct=2
        status.save()
        if status:
            return JsonResponse({'asg':1})


#删除自己发送的站内信
def deleteMySendMail(request):
    if request.method == 'POST':
        mail_id = request.POST.get('mail_id')
        from_user=request.POST.get('from_user')
        status = Mail.objects.get(mail_id=mail_id,from_user=from_user)
        status.defunct = 3
        status.save()
        if status:
            return JsonResponse({'asg': 1})


#个人赛报名
def signup(request):
    user_id = request.POST.get('user_id')
    contest_id = request.POST.get('contest_id')
    if user_id:
        contest_id_name = 'c' + str(contest_id)
        Privilege.objects.create(user_id=user_id, rightstr=contest_id_name, defunct='N')
        massage = {'err': 'True'}
        return JsonResponse(massage, safe=False)

#团队赛报名
def groupSignUp(request):
    user1 = request.POST.get('user1',1)
    user2 = request.POST.get('user2',1)
    user3 = request.POST.get('user3',1)
    team = request.POST.get('team')
    contest_id = request.POST.get('contest_id')
    if user1==1 and user2==1 and user3==1:
        massage = {'err': 'False'}
        return JsonResponse(massage, safe=False)
    if not contest_id or not team:
        massage = {'err':'Incomplete information'}
        return JsonResponse(massage, safe=False)
    if contest_id and team:
        Signup.objects.create(team = team,user1 = user1, user2=user2, user3=user3,contest_id = contest_id)
        for data in [user1,user2,user3]:
            if data != 1:
                contest_id_name = 'c' + str(contest_id)
                Privilege.objects.create(user_id=data, rightstr=contest_id_name, defunct='N')
    return JsonResponse({'err':'true'}, safe=False)


#新闻内容
def news(request):
    if request.method == 'GET':
        news_id = request.GET.get('news_id')
        news = News.objects.filter(news_id = news_id).first()
        news_data = []
        try:
            news_content = eval(news.content)
            if news_content.get('contest_type') == 1:
                contest_type = 1
            elif news_content.get('contest_type') == 2:
                contest_type = 2
            content = news_content.get('content')
            contest_id = news_content.get('contest_id')
        except:
            content = news.content
            contest_type = ''

            contest_id = 0
        news_data.append(
            {
                'news_id': news.news_id,
                'title': news.title,
                'content': content,
                'time': news.time,
                'contest_type':contest_type,
                'contest_id':contest_id,
                'image_path':news.image_path
            }
        )

        return JsonResponse(news_data, safe=False)

#我的状态
def userStatus(request):
    if request.method == 'GET':
        u_id = request.GET.get('u_id')
        user_id = request.GET.get('user_id')
    n_year = datetime.datetime.now().year
    n_month = datetime.datetime.now().month
    n_day = datetime.datetime.now().day

    num = 0
    submit_data = []
    solved_data = []
    date_data = []
    month = n_month
    s_month = month
    year = n_year - 1
    if n_day <= 15:
        day = 15
    elif n_day > 15:
        day = 1
    s_day = day
    endtime = None
    while True:
        day = oneAndFifteen(day)
        starttime = '{}-{}-{}'.format(year, timeChange(month), timeChange(day))
        if day == 15:
            month += 1
            if month == 13:
                month = 1
                year += 1

        if endtime:
            n_submit = getTimeSubmit(endtime, starttime, user_id)
            n_submit = n_submit[0][0]
            n_solved = getTimeSolved(endtime, starttime, user_id)
            n_solved = n_solved[0][0]
            submit_data.append(n_submit)
            solved_data.append(n_solved)
        day = oneAndFifteen(day)
        endtime = '{}-{}-{}'.format(year, timeChange(month), timeChange(day))

        num = num + 1
        submit = getTimeSubmit(starttime, endtime, user_id)
        solved = getTimeSolved(starttime, endtime, user_id)
        month = s_month + num
        if month == 13:
            year += 1
            month = 1
            num = 1
            s_month = 1
        submit = submit[0][0]
        solved = solved[0][0]
        submit_data.append(submit)
        solved_data.append(solved)
        date_data.append(starttime)
        date_data.append(endtime)
        if year == n_year and n_month == month and s_day == day:
            day = oneAndFifteen(day)
            starttime = '{}-{}-{}'.format(year, timeChange(month), timeChange(day))
            n_submit = getTimeSubmit(endtime, starttime, user_id)
            n_submit = n_submit[0][0]
            n_solved = getTimeSolved(endtime, starttime, user_id)
            n_solved = n_solved[0][0]
            submit_data.append(n_submit)
            solved_data.append(n_solved)
            date_data.append(starttime)
            break
    user = Users.objects.filter(user_id = user_id).all()
    user = changeToJson(user)
    solved = user[0]
    solved = solved['solved']
    rank = Users.objects.filter(solved__gt = solved).count()
    statistics = [0, 0, 0, 0, 0, 0, 0, 0,0]
    for i in range(4,13):
        statistics[i-4] = Solution.objects.filter(user_id = user_id, result = i).count()
    problem = getEveryResult(user_id)
    if verifyPrivilege(u_id)[0][0] == 1 or verifyPrivilege(u_id)[0][0] == 0:
        login = getLoginIp(user_id)
    else:
        login = ''
    result = {'user': user, 'problem': problem, 'statistics':statistics, 'rank':rank + 1, 'submit_data':submit_data, 'solved_data':solved_data, 'date_data':date_data,'login':login}
    return JsonResponse(result, safe=False)

#修改昵称、学校、性别信息页面
def setPersonalInfo(request):
    if request.method == 'POST':
        user_id = request.POST.get('user_id')
        new_school = request.POST.get('new_school')
        new_nick = request.POST.get('new_nick')
        new_sex = request.POST.get('new_sex')
        code = request.POST.get('code')
        user = Users.objects.filter(user_id=user_id).first()
        if check_capture(request, code):
            if new_school:
                user.school = new_school
                user.save()
            if new_nick:
                user.nick = new_nick
                user.save()
            if new_sex:
                user.sex = new_sex
                user.save()
            massage = {'err': 'modification succeeded'}
        else:
            massage = {'err':'Verification code error'}
        return JsonResponse(massage)
    if request.method == 'GET':
        res = pub.capture(request)
        return JsonResponse(res)

#我的收藏
def myCollection(request):
    if request.method == 'GET':
        user_id = request.GET.get('user_id')
        page = int(request.GET.get('page', '1'))
    Collection_data = Collection.objects.filter(user_id=user_id).values('problem_id')[(page-1)*50:page*50]
    total = Collection.objects.filter(user_id=user_id).count()
    problem_data = []
    for data in Collection_data:
        problem_id = data['problem_id']
        rsproblem = Problem.objects.filter(problem_id=problem_id)
        rsproblem = changeToJson(rsproblem)
        problem_data.append(rsproblem)
    result = {'problem': problem_data, 'page': page, 'total': total}
    return JsonResponse(result, safe=False)

#储存用户提交时的代码

def storeCode(request):
    if request.method == 'GET':
        solution_id = request.GET.get('s_id')
        int(solution_id)
        source = request.GET.get('source')
    Sid_judge=SourceCode.objects.filter(solution_id=solution_id).first()
    if Sid_judge==None:
        SourceCode.objects.create(solution_id=solution_id,source=source)
    else:
        SourceCode.objects.filter(solution_id=solution_id).update(source=source)
    Sid_judge = SourceCode.objects.filter(solution_id=solution_id).first()
    return JsonResponse({'storePass':Sid_judge.source}, safe=False)

#取出用户某次提交的代码
def takeoutCode(request):
    solution_id = request.GET.get('s_id')
    user_id = request.GET.get('user_id')
    solution = Solution.objects.filter(solution_id = solution_id).first()
    if user_id:
        if solution.user_id == user_id or verifyPrivilege(user_id)[0][0] == 1 or verifyPrivilege(user_id)[0][0] == 0 or JudgmentAuthority(user_id,'source_browser'):
            source = []
            code = SourceCode.objects.filter(solution_id = solution_id).first()
            code = code.source
            source.append({
                'code': code,
                'User': solution.user_id,
                'Problem': solution.problem_id,
                'Language': solution.language,
                'Result': solution.result,
                'memory':solution.memory,
                'time':solution.time
            })
            return JsonResponse(source, safe=False)
        else:
            return JsonResponse('No permission to view code', safe=False)
    else:
        return JsonResponse('Not signed in yet', safe=False)

#代码
def reInfo(request):
    solution_id = request.GET.get('s_id')
    user_id = request.GET.get('user_id')
    solution = Solution.objects.filter(solution_id = solution_id).first()
    if user_id:
        if solution.user_id == user_id or verifyPrivilege(user_id)[0][0] == 1 or verifyPrivilege(user_id)[0][0] == 0:
            source = []
            runerr = Runtimeinfo.objects.filter(solution_id=solution.solution_id).first()
            if runerr and solution.result == 6:
                runerr = runerr.error
            else:
                runerr = ''
            code = SourceCode.objects.filter(solution_id = solution_id).first()
            code = code.source
            source.append({
                'runerr': runerr,
                'code': code,
                'User': solution.user_id,
                'Problem': solution.problem_id,
                'Language': solution.language,
                'Result': solution.result,
                'memory':solution.memory,
                'time':solution.time,

            })
            return JsonResponse(source, safe=False)
        else:
            return JsonResponse('No permission to view code', safe=False)
    else:
        return JsonResponse('Not signed in yet', safe=False)

#开放课程演练——取关卡大类，关卡列表，关卡信息,课程进度,先决条件
def takeoutLevelinfo(request):
    user_id = request.GET.get('user_id',None)
    LevelKinds=LevelKind.objects.filter(kind_id__gt=7).order_by('kind_id')
    LevelKinds_dict=[] #各个关卡大类
    for data in LevelKinds:
        LevelKind_temp={}
        LevelKind_temp['kind_id']=data.kind_id
        LevelKind_temp['kind_title'] = data.kind_title
        LevelKind_temp['description'] = data.description
        kind_id=int(data.kind_id)
        Levels=Level.objects.filter(kind_id=kind_id).order_by('level_id')
        level_all = Level.objects.filter(kind_id=kind_id).count()
        level_now=0
        level_judge=1 #某大类先决#先决条件 0，可挑战 1，已通关 2 判定
        Levelinfos=[] #某大类关卡信息
        for data1 in Levels:
            level_judge = 1
            Levelinfo_temp={}
            Levelinfo_temp['level_id']=data1.level_id
            Levelinfo_temp['title'] = data1.title
            Levelinfo_temp['description'] = data1.description
            Levelinfo_temp['pass_num'] = data1.pass_num
            level_id=int(data1.level_id)
            sql=LevelPass.objects.filter(level_id=level_id,user_id=user_id).count()
            if sql == 1:
                level_now=level_now+1
                level_judge=2 #已通关
            else:
                temp=re.findall("(\d+)", data1.level_pre)
                filter(None, temp)
                if temp!=[]:
                    for level_pre_id in temp:
                        int(level_pre_id)
                        sql = LevelPass.objects.filter(level_id=level_pre_id, user_id=user_id).count()
                        if sql==0:
                            level_judge=0  #有先决条件
                            break
            Levelinfo_temp['level_judge'] =level_judge
            Levelinfos.append(Levelinfo_temp)

        #对通关的用户进行加分处理
        if level_judge==2:
            userinfo = Users.objects.get(user_id=user_id)
            userinfo.score += 30

        LevelKind_temp['level_all']=level_all
        LevelKind_temp['level_pass'] = level_now
        LevelKind_temp['Levels']=Levelinfos
        LevelKinds_dict.append(LevelKind_temp)
    return JsonResponse({"LevelKind":LevelKinds_dict}, safe=False)

#开放课程演练——取关卡题目列表信息,题目信息,先决关卡
def takeoutLevelpro(request):
    if request.method == 'POST':
        level_id = request.POST.get('level_id')
        level_judge = request.POST.get('level_judge')
    if level_judge=="0":  #先决关卡列表
        preinfos = []  #先决关卡列表
        Levelpre = Level.objects.filter(level_id=level_id)
        temp=[]
        for data in Levelpre:
            levelpre=data.level_pre
            temp = re.findall("(\d+)", levelpre)
            filter(None, temp)
        for level_pre_id in temp:
            preinfo={}
            level_nowjudge = Level.objects.filter(level_id=level_pre_id).first() #加个values 清除冗余字段,报错
            preinfo['title']=level_nowjudge.title
            preinfo['level_id']= level_nowjudge.level_id
            int(level_pre_id)
            c = connection.cursor()  # 原生sql查询
            sql = 'select * from level_pass where level_id=%s' % level_pre_id  # 查询操作
            if c.execute(sql)==1:
                c.close()
                continue
            c.close()
            preinfos.append(preinfo)
        return JsonResponse({"Preinfo":preinfos}, safe=False)
    else: #题目列表及信息
        LevelPros = []  # 题目列表信息
        id = int(level_id)  # 转为整型，level_problem及level_pass表 level_id 为整型
        with connection.cursor() as cursor:
            cursor.execute("SELECT * FROM level_problem WHERE level_id = %s", [id])
            solution_data = cursor.fetchall()
        level_problems = list(solution_data)
        for data in level_problems:
            problem_id=data[0]
            proinfos = {}  # 各个题目信息
            proinfo_part = Problem.objects.filter(problem_id=problem_id).first()
            if proinfo_part:
                proinfos['problem_id'] = proinfo_part.problem_id
                proinfos['title'] = proinfo_part.title
                proinfos['solved'] = proinfo_part.solved
                LevelPros.append(proinfos)
            else:
                proinfos['problem_id'] = problem_id
                proinfos['title'] = ''
                proinfos['solved'] = ''
                LevelPros.append(proinfos)
        return JsonResponse({"Proinfo":LevelPros},safe=False)

#管理员新闻列表
def adminNewList(request):
    if request.method == 'POST':
        admin = request.POST.get('admin')
        if not (verifyPrivilege(admin)[0][0] == 1 or verifyPrivilege(admin)[0][0] == 0):
            massage = {'err': 'Insufficient authority'}
            return JsonResponse(massage, safe=False)
    content = request.POST.get('content','')
    page = int(request.POST.get('page', '1'))
    news = News.objects.filter(Q(news_id__contains=content) | Q(title__contains=content)).order_by('-time')[(page-1)*50:page*50]
    total = News.objects.filter(Q(news_id__contains=content) | Q(title__contains=content)).count()
    news_data = []
    for data in news:
        if data.defunct == 'N':
            defunct = 'On'
        else:
            defunct = 'Off'
        if data.importance == 1:
            importance = 'Yes'
        else:
            importance = 'No'
        news_data.append(
            {
                'news_id': data.news_id,
                'title': data.title,
                'time': data.time,
                'defunct':defunct,
                'importance':importance

            }
        )
    result = {'news': news_data, 'page': page, 'total': total}
    return JsonResponse(result, safe=False)

#新闻接收图片
def receiveImage(request):

    if request.method == "POST":
        admin = request.POST.get('admin')
        if not (verifyPrivilege(admin)[0][0] == 1 or verifyPrivilege(admin)[0][0] == 0):
            massage = {'err': 'Insufficient authority'}
            return JsonResponse(massage, safe=False)


        imageList = request.FILES.getlist('image', '')
        for imageInfo in imageList:

            if imageInfo:

                with open("/home/jhcoj/data/news/%s" % imageInfo.name, 'wb+') as f:
                    # with open("../data/news/%s" %title, 'wb+') as f:
                    # 分块写入文件
                    for chunk in imageInfo.chunks():
                        f.write(chunk)
                image_path = '/home/jhcoj/data/news/' + imageInfo.name
                # image_path ='../data/news/'+ title

                massage = {'err': 'successful','adress':image_path}
                return JsonResponse(massage, safe=False)
            else:
                image_path = ''

                massage = {'err': 'false'}
                return JsonResponse(massage, safe=False)

#接受问题的图片
def receiveImageOfProblem(request):

    if request.method == "POST":
        admin = request.POST.get('admin')
        if not (verifyPrivilege(admin)[0][0] == 1 or verifyPrivilege(admin)[0][0] == 0):
            massage = {'err': 'Insufficient authority'}
            return JsonResponse(massage, safe=False)


        imageList = request.FILES.getlist('image', '')
        for imageInfo in imageList:

            if imageInfo:

                with open("/home/jhcoj/data/problem/%s" % imageInfo.name, 'wb+') as f:
                    # with open("../data/news/%s" %title, 'wb+') as f:
                    # 分块写入文件
                    for chunk in imageInfo.chunks():
                        f.write(chunk)
                image_path = '/home/jhcoj/data/problem/' + imageInfo.name
                # image_path ='../data/news/'+ title

                massage = {'err': 'successful','adress':image_path}
                return JsonResponse(massage, safe=False)
            else:
                image_path = ''

                massage = {'err': 'false'}
                return JsonResponse(massage, safe=False)

#新闻轮播图
def NewsRotations(request):
    newslist = News.objects.filter(image=1).order_by('-news_id')[:4]
    news_data=[]
    for news in newslist:
        news_data.append(
            {
                'news_id': news.news_id,
                'title': news.title,
                'content': news.content,
                'time': news.time,
                'image_path':news.image_path,
                'contest_id': news.user_id,

            }
        )
    return JsonResponse(news_data,safe=False)




#添加新闻
def addNews(request):
    admin = request.POST.get('admin')
    if not (verifyPrivilege(admin)[0][0] == 1 or verifyPrivilege(admin)[0][0] == 0):
        massage = {'err': 'Insufficient authority'}
        return JsonResponse(massage, safe=False)
    user_id = request.POST.get('admin', '')
    title = request.POST.get('title','')
    content = request.POST.get('content','')
    image = request.POST.get('image' , '')


    #a = str(content)

   # path = re.search('<img src="(.*)">', content)

    path = str(re.findall(r'.*<img src="(.*)">', content)).replace("']", "").replace("['","")

    if path:
        if image:

            # with open("../data/news/%s" % image.name, 'wb+') as f:
            # # with open("../data/news/%s" %title, 'wb+') as f:
            #     # 分块写入文件
            #     for chunk in image.chunks():
            #         f.write(chunk)
            image_path = path
            #image_path ='../data/news/'+ title
            image_P = 1
        else:
            image_path = ''
            image_P = 0
        importance = request.POST.get('importance','0')
        defunct = request.POST.get('defunct','N')
        time_n = datetime.datetime.now()
        if title and content:
            News.objects.create(
                user_id = user_id,
                title = title,
                content = content,
                image = image_P,
                image_path = image_path,
                importance = importance,
                time = time_n,
                defunct = defunct
            )
            obj = 'Saved successfully'
        elif not title and not content:
            obj = 'title and content not entered'
        elif not title:
            obj = 'title not entered'
        elif not content:
            obj = 'content not entered'
        return JsonResponse(obj, safe=False)

    else:
        obj = 'path is null'
        return JsonResponse(obj, safe=False)


#编辑新闻
def editNews(request):
    if request.method == 'POST':
        admin = request.POST.get('admin')
        if not (verifyPrivilege(admin)[0][0] == 1 or verifyPrivilege(admin)[0][0] == 0):
            massage = {'err': 'Insufficient authority'}
            return JsonResponse(massage, safe=False)
        news_id = request.POST.get('news_id')
        title = request.POST.get('title')
        content = request.POST.get('content')
        image = request.POST.get('image')
        importance = request.POST.get('importance')
        defunct = request.POST.get('defunct')
        new = News.objects.filter(news_id=news_id).first()
        if title:
            new.title = title
            new.save()
        if content:
            new.content = content
            new.save()
        if image:


            path = str(re.findall(r'.*<img src="(.*)">', content)).replace("']", "").replace("['", "")

            new.image = 1
            new.path=path
            new.save()
        if importance:
            if new.importance == 0:
                new.importance = 1
                new.save()
            else:
                new.importance = 0
                new.save()
            return JsonResponse('ture', safe=False)
        if defunct:
            if new.defunct == 'N':
                new.defunct = 'Y'
                new.save()
            elif new.defunct == 'Y':
                new.defunct = 'N'
                new.save()
            return JsonResponse('ture', safe=False)
        return JsonResponse('ture', safe=False)
    elif request.method == 'GET':
        news_id = request.GET.get('news_id')
        rsnew = News.objects.filter(news_id=news_id).all()
        rsnew = changeToJson(rsnew)
        return JsonResponse(rsnew, safe=False)


#删除新闻
def deleteNews(request):
    if request.method == 'GET':
        admin = request.GET.get('admin')
        if not (verifyPrivilege(admin)[0][0] == 1 or verifyPrivilege(admin)[0][0] == 0):
            massage = {'err': 'Insufficient authority'}
            return JsonResponse(massage, safe=False)
        news_id = request.GET.get('news_id')
    if news_id:
        News.objects.filter(news_id = news_id).delete()
        new = News.objects.filter(news_id = news_id).first()
        if not new:
            massage = {'err': '删除成功'}
        else:
            massage = {'err':'删除错误'}
        return JsonResponse(massage, safe=False)

#用户列表
def usersList(request):
    if request.method == 'GET':
        admin = request.GET.get('admin')
        if not (verifyPrivilege(admin)[0][0] == 1 or verifyPrivilege(admin)[0][0] == 0):
            massage = {'err': 'Insufficient authority'}
            return JsonResponse(massage, safe=False)
        page = int(request.GET.get('page','1'))
        content = request.GET.get('content','')
    total = Users.objects.filter(Q(user_id__contains=content) | Q(nick__contains=content)).count()
    users = Users.objects.filter(Q(user_id__contains=content) | Q(nick__contains=content)).order_by('-reg_time').all()[(page-1)*50:page*50]
    users = changeToJson(users)
    rs = {'user':users,'total':total}
    return JsonResponse(rs, safe=False)

#删除用户
def deleteUsers(request):
    if request.method == 'POST':
        admin = request.POST.get('admin')
        if not (verifyPrivilege(admin)[0][0] == 1 or verifyPrivilege(admin)[0][0] == 0):
            massage = {'err': 'Insufficient authority'}
            return JsonResponse(massage, safe=False)
        user_id = request.POST.get('user_id')
        Users.objects.filter(user_id = user_id).delete()
        user = Users.objects.filter(user_id = user_id).first()
        if user:
            massage = {'err':'False'}
        else:
            massage = {'err': 'Ture'}
        return JsonResponse(massage, safe=False)

#更改用户状态
def changeUserStatus(request):
    if request.method == 'POST':
        admin = request.POST.get('admin')
        if not (verifyPrivilege(admin)[0][0] == 1 or verifyPrivilege(admin)[0][0] == 0):
            massage = {'err': 'Insufficient authority'}
            return JsonResponse(massage, safe=False)
        user_id = request.POST.get('user_id')
    user = Users.objects.filter(user_id = user_id).first()
    if user:
        if user.defunct == 'N':
            user.defunct = 'Y'
            user.save()
        else:

            user.defunct = 'N'
            user.save()
        massage = {'err':'Saved successfully!'}
    else:
        massage= {'err':'No Such User!'}
    return JsonResponse(massage, safe=False)

#修改密码
def resetPwd(request):
    if request.method == 'POST':
        oldpassword = request.POST.get('oldpassword')
        newpassword = request.POST.get('newpassword')
        qrpassword = request.POST.get('qrpassword')
        user_id = request.POST.get('user_id')
        code = request.POST.get('code')
        user = Users.objects.filter(user_id=user_id).first()
        if oldpassword and newpassword and qrpassword and code:
            if newpassword == qrpassword:
                if check_capture(request, code):
                    if checkPassword(oldpassword,user.password) or md5CheckPassword(oldpassword,user.password):
                        newpassword = reg_pass(newpassword)
                        user.password = newpassword
                        user.save()
                        massage = {'err': 'modification succeeded!'}
                    else:
                        massage = {'err':'old password error'}
                else:
                    massage = {'err': 'Verification code error'}
            else:
                massage = {'err':'Confirm password error'}
        else:
            massage = {'err':'Incomplete information'}
        return JsonResponse(massage, safe=False)
    if request.method == 'GET':
        res = pub.capture(request)
        return JsonResponse(res)

#题目提交状态
def statusSubmit(request):
    if request.method == 'GET':
        problem_id = request.GET.get('problem_id')
        cpage = request.GET.get('cpage','1')
        int(problem_id)
    RNP=[] #推荐题目
    Statistics={}  #统计
    Status=[] #状态列表
    ranking=1 #名次
    # arr = ["等待....", "等待重判", "编译中...", "运行并评判", "正确", "格式错误", "答案错误",
    # "时间超限", "内存超限", "输出超限", "运行错误", "编译错误","运行完成"];
    language_name = ["C", "C++", "Pascal", "Java", "Ruby", "Bash", "Python", "PHP", "Perl", "C#", "Obj-C","FreeBasic", "Scheme", "Clang", "Clang++", "Lua", "JavaScript", "Go", "Other Language"]
    Statistics['submit_all']=Solution.objects.filter(problem_id=problem_id).count()
    Statistics['user_all']=Solution.objects.filter(problem_id=problem_id).values('user_id').distinct().count()
    Statistics['user_all_pass']=Solution.objects.filter(problem_id=problem_id,result=4).values('user_id').distinct().count()
    Statistics['pass']=Solution.objects.filter(problem_id=problem_id,result=4).count()
    Statistics['format_error']=Solution.objects.filter(problem_id=problem_id,result=5).count()
    Statistics['answer_error']=Solution.objects.filter(problem_id=problem_id,result=6).count()
    Statistics['time_out'] = Solution.objects.filter(problem_id=problem_id,result=7).count()
    Statistics['memory_out'] = Solution.objects.filter(problem_id=problem_id,result=8).count()
    Statistics['output_out'] = Solution.objects.filter(problem_id=problem_id,result=9).count()
    Statistics['runing_error'] = Solution.objects.filter(problem_id=problem_id,result=10).count()
    Statistics['compile_error'] = Solution.objects.filter(problem_id=problem_id,result=11).count()
    allPage=Statistics['submit_all']/20
    if isinstance(allPage,int):
        Statistics['Allpage']=allPage
    else:
        Statistics['Allpage'] = int(allPage)+1
    R=Problem.objects.exclude(problem_id=problem_id).values('problem_id')[:125]
    for data in R:
        RNP.append(data['problem_id'])
    total = Solution.objects.filter(problem_id=problem_id).count()
    Sta = Solution.objects.filter(problem_id=problem_id).order_by('memory', 'code_length')[(int(cpage)-1)*20:int(cpage)*20]
    for data in Sta:
        temp={}
        temp['ranking']=ranking
        ranking+1
        temp['solution_id']=data.solution_id
        temp['user_id'] = data.user_id
        temp['memory'] = data.memory
        temp['time'] = data.time
        temp['language'] = language_name[data.language]
        temp['code_length'] = data.code_length
        temp['in_date'] = data.in_date
        Status.append(temp)
    result={ 'Statistics': Statistics,'RNP': RNP,'Status':Status,'total':total}
    return JsonResponse(result,safe=False)


#判断用户是否填写真实姓名
def judgeRealName(request):
    if request.method =='POST':
        user_id = request.POST.get('user_id')
        real_name = Users.objects.filter(user_id=user_id,real_name='').first()
        if real_name is None:
            return JsonResponse({'message':'False'})
        else:
            return JsonResponse({'message': 'True'})


#设置真实姓名
def setRealName(request):
    if request.method == 'POST':
        user_id = request.POST.get('user_id')
        real_name = request.POST.get('real_name')
        confirm_name = request.POST.get('confirm_name')
        code = request.POST.get('code')
        user = Users.objects.filter(user_id = user_id).first()
        if check_capture(request, code):
            if real_name and confirm_name:
                if real_name == confirm_name:
                    user.real_name = real_name
                    user.save()
                    massage = {'err':'Set successfully'}
                else:
                    massage = {'err':'confirm password error'}
            else:
                massage = {'err': 'incomplete information'}
        else:
            massage = {'err':'verification code error'}
        return JsonResponse(massage, safe=False)
    if request.method == 'GET':
        user_id = request.GET.get('user_id')
        user = Users.objects.filter(user_id=user_id).first()
        if user.real_name:
            massage = 'false'
        else:
            massage = 'true'
        res = pub.capture(request)
        res['massage'] = massage
        return JsonResponse(res)

#我的题解
def myProblemSolution(request):
    if request.method == 'GET':
        author_id = request.GET.get('user_id')
        page = request.GET.get('page','1')
    if author_id:
        problemSolution = Topic.objects.filter(author_id=author_id)[(int(page)-1)*30:int(page)*30]
        totle = Topic.objects.filter(author_id=author_id).count()
        problemSolution_data = []
        for data in problemSolution:
            if data.defunct == 'N':
                massage = 'approved'
            else:
                massage = 'under review'
            problemSolution_data.append(
                {
                    'pid':data.pid,
                    'title':data.title.decode('utf-8'),
                    'massage':massage,
                    'content':data.content,
                    'time':data.time,
                    'author_id': author_id
                }
            )
        massage = {'problemSolution_data': problemSolution_data, 'totle': totle,}
        return JsonResponse(massage, safe=False)
    else:
        massage = {'massage':"You don't have access"}
        return JsonResponse(massage,safe = False)

#添加或取消收藏
def addordelCollection(request):
    if request.method == 'GET':
        user_id = request.GET.get('user_id')
        problem_id = request.GET.get('problem_id')
    if str(user_id) == '' or user_id is None:
        massage = {
            'err':'Please login and try again'
        }
        return JsonResponse(massage, safe=False)#如果用户没有登录，提示用户 '请登录后重试'
    collectioninfo = Collection.objects.filter(user_id__exact=user_id, problem_id__exact=problem_id)
    if collectioninfo.count() == 0:
        save_collection = Collection(user_id=user_id ,problem_id=problem_id)
        save_collection.save()#添加收藏
        massage = { 'err':'Collection success' }
        return JsonResponse(massage, safe=False)#返回收藏成功
    else:
        collectioninfo.delete()
        massage = {'err': 'Collection cancelled successfully'}
        return JsonResponse(massage, safe=False)#返回成功取消收藏


#插入限制的用户ip和时间
def setIp(request):
    if request.method == 'POST':
        user_id = request.POST.get('user_id')
        start_time = time.strftime("%Y-%m-%d %H:%M:%S", time.localtime())
        info = UserIp.objects.create(
            user_id=user_id,
            start_time=start_time,
            during=''
        )
        if info :
            return JsonResponse({'message':'successfully added '},safe=False)
        else:
            return JsonResponse({'message': 'addition failed '}, safe=False)


# 查找该用户是否被限制
def findIp(request):
    if request.method =='POST':
        user_id = request.POST.get('user_id')
        find = UserIp.objects.filter(user_id=user_id).order_by('start_time')
        if not find :
            return JsonResponse({'message': 'False '}, safe=False)
        else:
            find = changeToJson(find)
            return JsonResponse(find, safe=False)

#验证管理员身份
def verifyIdentiy(request):
    if request.method =='GET':
        user_id = request.GET.get('user_id')
    temp=verifyPrivilege(user_id)
    return  JsonResponse({'Privileges':temp},safe=False)

#获取当前用户的昵称,学校,性别
def userInfo(request):
    if (request.method == 'GET'):
        user_id = request.GET.get('user_id')
    if (str(user_id) == '' or user_id is None):
        massage = {
            'err':'Please login and try again'
        }
        return JsonResponse(massage, safe=False)#如果用户没有登录，提示用户 '请登录后重试'
    userinfo = Users.objects.values("user_id","school","sex").filter(user_id__exact = user_id)
    if(userinfo.count() == 0):
        massage = {
            'err': 'There is no such user. Please register and try again .'
        }
        return JsonResponse(massage, safe=False)
    userinfo = list(userinfo)
    return JsonResponse(userinfo[0], safe=False)

#找回密码
def findPass(request):
    if request.method == 'POST':
        user_id = request.POST.get('user_id')
        email = request.POST.get('email')
        new_paw = request.POST.get('new_paw')
        code = request.POST.get('code')
        user = Users.objects.filter(user_id = user_id).first()
        if check_capture(request, code):
            if user.email == email:
                ip = get_ip(request)
                redis.setex(ip + 'email', 600, email)

                paw = {'new_paw':new_paw,'user_id':user_id}
                redis.setex(email + '_check', 600, str(paw))
                massage = {'err': 'Ture'}
            else:
                massage = {'err':'user_id and mailbox do not match'}
        else:
            massage = {"err": "verification code error"}
        return JsonResponse(massage, safe=False)
    if request.method == 'GET':
        res = pub.capture(request)
        return JsonResponse(res)

#验证邮箱验证码 并修改密码
def emailChangePass(request):
    email = request.POST.get('email')
    code = request.POST.get('email_capture')
    paw = redis.get(email + '_check')
    if paw:
        a = paw.decode('utf-8', 'ignore').replace('\'', '"')
        paw = json.loads(a)
        user_id = paw['user_id']
        if pub.check_email_code(email,code):
            obj = Users.objects.filter(user_id = user_id).first()
            obj.password = reg_pass(paw['new_paw'])
            obj.save()
            if obj:
                state = {"err": 'True'}
                return JsonResponse(state)
        else:
            state = {"err": 'Verification code error'}
            return JsonResponse(state)
    else:
        state = {"err": 'The user does not exist.'}
        return JsonResponse(state)

#管理员关卡大类
def levelKind(request):
    if request.method == 'POST':
        admin = request.POST.get('admin')
        if not (verifyPrivilege(admin)[0][0] == 1 or verifyPrivilege(admin)[0][0] == 0):
            massage = {'err': 'Insufficient authority'}
            return JsonResponse(massage, safe=False)
    if request.method == 'POST':
        cpage = int(request.POST.get('cpage','1'))
        edit=request.POST.get('editKind_id',None)
        delete = request.POST.get('deleteId', None)
        addKindId=request.POST.get('kind_id',None)
        addKindTitile=request.POST.get('kind_title',None)
        addKindDescription=request.POST.get('description','no description')
    if delete!=None:   #删除整个关卡大类及分支关卡
        LevelKind.objects.filter(kind_id=delete).delete()
        levelinfos=Level.objects.filter(kind_id=int(delete)).all()
        deleteLevelPro = 'Error or No Levels'
        for data in levelinfos:
            levelinfo = Level.objects.filter(level_id=data.level_id).first()
            temp = re.findall("(\d+)", levelinfo.level_pre)
            filter(None, temp)
            if temp != []:
                for problemId in temp:
                    LevelProblem.objects.filter(level_id=int(data.level_id), problem_id=int(problemId)).delete()
                    deleteLevelPro = 'deletePass'
            Level.objects.filter(level_id=data.level_id).delete()
        Level.objects.filter(kind_id=int(delete)).delete()
        return JsonResponse(deleteLevelPro, safe=False)
    if edit!=None:  #返回待编辑的数据
        temp = {}
        levelKind=LevelKind.objects.filter(kind_id=edit).first()
        temp['kind_title'] = levelKind.kind_title
        temp['description'] = levelKind.description
        return JsonResponse({'editInfo':temp},safe=False)
    if addKindTitile!=None:
        if addKindId==None:
            LevelKind.objects.create(kind_title=addKindTitile,description=addKindDescription)
            return JsonResponse('createPass', safe=False)
        else:
            LevelKind.objects.filter(kind_id=addKindId).update(kind_title=addKindTitile, description=addKindDescription)
            return JsonResponse('editPass', safe=False)
    levelKinds = LevelKind.objects.filter().order_by('kind_id')[(cpage-1)*10:cpage*10]
    kindInfos=[]
    for data in levelKinds:
        temp={}
        temp['kind_id']=data.kind_id
        temp['kind_title'] = data.kind_title
        temp['description'] = data.description
        kindInfos.append(temp)
    kindAll=LevelKind.objects.filter().count()
    total=kindAll
    allPage = kindAll/ 10
    if isinstance(allPage, int):
        kindAll = allPage
    else:
        kindAll= int(allPage) + 1
    return JsonResponse({'levelKind':kindInfos,'pageAll':kindAll,'total':total,'cpage':cpage},safe=False)

#管理员关卡列表
def levels(request):
    if request.method == 'POST':
        admin = request.POST.get('admin')
        if not (verifyPrivilege(admin)[0][0] == 1 or verifyPrivilege(admin)[0][0] == 0):
            massage = {'err': 'Insufficient authority'}
            return JsonResponse(massage, safe=False)
        delete=request.POST.get('deleteId',None)  #返回待编辑内容的edit功能在 修改关卡 接口内
        if delete!=None:
            deleteLevelPro='Error or No LevelProblem'
            levelinfo = Level.objects.filter(level_id=delete).first()
            temp = re.findall("(\d+)", levelinfo.level_pre)
            filter(None, temp)
            if temp != []:
                for problemId in temp:
                    LevelProblem.objects.filter(level_id=int(delete), problem_id=int(problemId)).delete()
                    deleteLevelPro = 'deletePass'
            Level.objects.filter(level_id=delete).delete()
            return JsonResponse(deleteLevelPro, safe=False)
    if request.method == 'GET':
        cpage = int(request.GET.get('cpage','1'))
        search=request.GET.get('titleOrDescription',None)

    kinds=LevelKind.objects.filter().order_by('kind_id').values('kind_id','kind_title')
    kindInfos=[]
    for data in kinds:
        temp = {}
        temp['kind_id'] = data['kind_id']
        temp['kind_title'] = data['kind_title']
        kindInfos.append(temp)
    if search!=None:  #查询功能
        levels=Level.objects.filter(Q(title__contains=search)|Q(description__contains=search))[(cpage-1)*20:cpage*20]
        levelAll=Level.objects.filter(Q(title__contains=search)|Q(description__contains=search)).count()
    else:
        levels=Level.objects.filter().order_by('kind_id')[(cpage-1)*20:cpage*20]
        levelAll = Level.objects.filter().count()
    levelInfos=[]
    for data in levels:
        temp={}
        temp['level_id'] = data.level_id
        temp['title'] = data.title
        temp['description'] = data.description
        temp['level_pre'] = data.level_pre
        temp['pass_num'] = data.pass_num
        temp['kind_id'] = data.kind_id
        levelInfos.append(temp)
    total = levelAll
    allPage = levelAll / 20
    if isinstance(allPage, int):
        allPage = allPage
    else:
        allPage = int(allPage) + 1
    return JsonResponse({'levels': levelInfos, 'kinds':kindInfos, 'total': total, 'allPage': allPage, 'cpage': cpage}, safe=False)

#管理员添加/修改关卡
def addLevel(request):
    if request.method == 'POST':
        admin = request.POST.get('admin')
        if not (verifyPrivilege(admin)[0][0] == 1 or verifyPrivilege(admin)[0][0] == 0):
            massage = {'err': 'Insufficient authority'}
            return JsonResponse(massage, safe=False)
        editLevelId=request.POST.get('level_id',None)
        addTitle=request.POST.get('title',None)
        addDescription = request.POST.get('description', 'no description')
        addPass_num = request.POST.get('pass_num', None)
        addKind_id = request.POST.get('kind_id', None)
        addProblem = request.POST.get('problems', None)
        addLevel_pre =request.POST.get('level_pre', None)
    if addTitle!=None and addProblem!=None and addPass_num!=None :  #添加关卡/修改关卡,显示修改关卡页面
        if editLevelId!=None: #修改关卡
            Level.objects.filter(level_id=int(editLevelId)).update(title=addTitle,description=addDescription,level_pre=addLevel_pre,pass_num=addPass_num,kind_id=addKind_id)
            result='editPass'
        else: #添加关卡
            insertRes = Level.objects.create(title=addTitle,description=addDescription,level_pre=addLevel_pre,pass_num=addPass_num,kind_id=addKind_id)
            editLevelId=insertRes.level_id
            result = 'createPass'
        temp = re.findall("(\d+)", addProblem)   #修改/新增关卡题目
        filter(None, temp)
        num = LevelProblem.objects.filter(level_id=int(editLevelId)).count()
        if temp != []:
            for problemId in temp:
                existPronblem =Problem.objects.filter(problem_id=int(problemId)).count()
                if existPronblem == 0:
                    return JsonResponse('editPass or createPass,but %s problem is null,please go to edit Level'%problemId, safe=False)
                existPronblem =LevelProblem.objects.filter(level_id=int(editLevelId),problem_id=int(problemId)).count()
                if existPronblem==0:
                    num+1
                    LevelProblem.objects.create(level_id=int(editLevelId),problem_id=int(problemId),num=num)
        return JsonResponse(result, safe=False)
    if addKind_id!=None:    #先导关卡列表
        levels = Level.objects.filter(kind_id=int(addKind_id)).order_by('level_id').values('level_id', 'title')
        levelInfos = []
        for data in levels:
            temp = {}
            temp['kind_id'] = data['level_id']
            temp['kind_title'] = data['title']
            levelInfos.append(temp)
        return JsonResponse({'levelInfos': levelInfos}, safe=False)
    if editLevelId!=None:  #修改关卡页面
        levelinfo=Level.objects.filter(level_id=editLevelId).first()
        levelinfos={}
        levelinfos['level_id'] = levelinfo.level_id
        levelinfos['title'] = levelinfo.title
        levelinfos['description'] = levelinfo.description
        pres=[]
        temp = re.findall("(\d+)", levelinfo.level_pre)  # 修改/新增关卡题目
        filter(None, temp)
        if temp != []:
            for level_pre_id in temp:
                pres.append(level_pre_id)
        levelinfos['level_pre'] = pres
        levelinfos['pass_num'] = levelinfo.pass_num
        levelinfos['kind_id'] = levelinfo.kind_id
        levelProblems=LevelProblem.objects.values('level_id').annotate(problem_ids=Concat('problem_id')).get(level_id=int(editLevelId))
        problems=levelProblems['problem_ids']
        kindLevel=Level.objects.filter(kind_id=levelinfos['kind_id'])
        kindLevels=[]
        for data in kindLevel:
            if str(data.level_id)!=editLevelId:
                temp={}
                temp['level_id'] = data.level_id
                temp['title'] = data.title
                kindLevels.append(temp)
        return JsonResponse({'levelinfos': levelinfos,'levelProblems': problems,'kindLevels': kindLevels}, safe=False)

#添加留言
def addReply(request):
    if (request.method == 'GET'):
        author_id = request.GET.get('author_id',None)
        content = request.GET.get('content',None)
        topic_id = request.GET.get('topic_id',None)
        status = request.GET.get('status',None)
    time = timezone.now()
    ip = get_ip(request)
    if str(author_id).replace(" ","") == '':
        massage = {
            'err': 'Author_id cannot be empty. Please login and try again.'
        }
        return JsonResponse(massage, safe=False)
    if (str(content).replace(" ","")==''):
        massage = {
            'err': 'Content cannot be empty'
        }
        return JsonResponse(massage, safe=False)#提示内容不能为空
    if (str(topic_id).replace(" ","")==''):
        massage = {
            'err': 'Topic_id cannot be empty'
        }
        return JsonResponse(massage, safe=False)#提示标题ID不能为空
    judge = Topic.objects.filter(topic_id__exact=topic_id)
    if (len(judge) == 0):
        massage = {
            'err': 'The title does not exist'
        }
        return JsonResponse(massage, safe=False)#提示该标题不存在
    if (str(status).replace(" ","")==''):
        massage = {
            'err': 'Status cannot be empty'
        }
        return JsonResponse(massage, safe=False)#提示状态不能为空
    add_reply = Reply(author_id=author_id,time=time,content=content,topic_id=topic_id,status=status,ip=ip)
    add_reply.save()
    massage = {'err':'Message added successfully'}
    return JsonResponse(massage, safe=False)

#审核题解回复页面
def checkReply(request):
    if request.method == 'GET':
        user_id = request.GET.get('user_id')
    topic = Topic.objects.filter(author_id=user_id).values('topic_id')
    list_reply = []
    for data in topic:
        data = data['topic_id']
        reply = Reply.objects.filter(topic_id=data).all()
        for reply_data in reply:
            list_reply.append(
                {
                    'author_id':reply_data.author_id,
                    'time':reply_data.time,
                    'content':reply_data.content,
                    'topic_id':reply_data.topic_id,
                }
            )
    return JsonResponse(list_reply, safe=False)

#题解留言通过
def passReply(request):
    if request.method == 'GET':
        r_id = request.GET.get('r_id')
    reply = Reply.objects.filter(r_id=r_id).first()
    if reply.status == 0:
        reply.status = 1
        reply.save()
        massage = {'err':'Audit successful'}
    elif reply.status == 1:
        reply.status == 0
        reply.save()
        massage = {'err':'Audit failed'}
    return JsonResponse(massage, safe=False)


#题解留言删除
def deleteReply(request):
    if request.method == 'GET':
        r_id = request.GET.get('r_id')
    Reply.objects.filter(r_id=r_id).delete()
    massage = {'err':'Delete succeeded'}
    return JsonResponse(massage, safe=False)


#管理员通关情况
def levelAccept(request):
    if request.method == 'POST':
        admin = request.POST.get('admin')
        if not (verifyPrivilege(admin)[0][0] == 1 or verifyPrivilege(admin)[0][0] == 0):
            massage = {'err': 'Insufficient authority'}
            return JsonResponse(massage, safe=False)
    if request.method == 'GET':
        class_id = request.GET.get('class_id',None)
        kind_id = request.GET.get('kind_id', None)
    if class_id!=None and kind_id!=None:
        levelAccept = []
        field=['user_id','user_name']
        levelInfo=Level.objects.filter(kind_id=int(kind_id))
        levels=[]
        for data in levelInfo:
            levels.append(int(data.level_id))
            field.append(data.title)
        classInfo=UserClass.objects.filter(class_id=int(class_id))
        userClass=[]
        for data in classInfo:
            name=Users.objects.get(user_id=data.user_id)
            temp = {'user_id': data.user_id, 'nick': name.nick}
            userClass.append(temp)
        for user in userClass:
            temp=[]
            temp.append(user['user_id'])
            temp.append(user['nick'])
            for level_id in levels:
                aceptJudge=LevelPass.objects.filter(user_id=user['user_id'],level_id=level_id).count()
                if aceptJudge==0:
                    temp.append('未通过')
                else:
                    temp.append('通过')
            levelAccept.append(temp)
        return JsonResponse({'field':field,'levelAccept':levelAccept},safe=False)
    classInfo=Class.objects.filter()
    classInfos=[]
    for data in classInfo:
        temp={}
        temp['class_id']=data.class_id
        temp['class_name'] = data.class_name
        classInfos.append(temp)
    kindInfo = LevelKind.objects.filter()
    kindInfos = []
    for data in kindInfo:
        temp = {}
        temp['kind_id'] = data.kind_id
        temp['kind_title'] = data.kind_title
        kindInfos.append(temp)
    return JsonResponse({'classInfos':classInfos,'kindInfos':kindInfos},safe=False)



#管理员添加问题
def addProblem(request):
    if request.method == 'POST':
        admin = request.POST.get('admin')
        if not (verifyPrivilege(admin)[0][0] == 1 or verifyPrivilege(admin)[0][0] == 0 or JudgmentAuthority(admin,'problem_editor')):
            massage = {'err': 'Insufficient authority'}
            return JsonResponse(massage, safe=False)
    if request.method == 'GET':
        problem_id = request.GET.get('problem_id')
        ProblemInfo={}
        temp=Problem.objects.get(problem_id=problem_id)
        ProblemInfo['title'] = temp.title
        ProblemInfo['time_limit'] = temp.time_limit
        ProblemInfo['memory_limit'] = temp.memory_limit
        ProblemInfo['description'] = temp.description
        ProblemInfo['input'] = temp.input
        ProblemInfo['output'] = temp.output
        ProblemInfo['sample_input'] = temp.sample_input
        ProblemInfo['sample_output'] = temp.sample_output
        aIn=test_read(problem_id,'test.in')
        aOut=test_read(problem_id,'test.out')
        if aIn!=None and aOut!=None:
            ProblemInfo['testIn'] = aIn
            ProblemInfo['testOut'] = aOut
        ProblemInfo['spj'] = temp.spj
        ProblemInfo['hint'] = temp.hint
        ProblemInfo['source'] = temp.source
        ProblemInfo['difficulty'] = temp.difficulty
        ProblemInfo['type'] = temp.type
        contestInfo=[]
        contestSet=Contest.objects.filter(start_time__gt=datetime.datetime.now())
        for data in contestSet:
            temp={}
            temp['contest_id']=data.contest_id
            temp['title']=data.title
            contestInfo.append(temp)
        return JsonResponse({'ProblemInfo':ProblemInfo,'contestInfo':contestInfo},safe=False)
    if request.method == 'POST':
        dct = {}
        problem_id = request.POST.get('problem_id')
        dct['title'] = request.POST.get('title')
        dct['time_limit'] = int(request.POST.get('time_limit'))
        dct['memory_limit'] =int( request.POST.get('memory_limit'))
        dct['description'] = request.POST.get('description')
        dct['input']= request.POST.get('input','')
        dct['output'] = request.POST.get('output','')
        dct['sample_input']= request.POST.get('sample_input','')
        dct['sample_output']= request.POST.get('sample_output','')
        testIn=request.POST.get('testIn', None)
        testOut=request.POST.get('testOut', None)
        dct['spj']= request.POST.get('spj', '0')
        dct['hint']= request.POST.get('hint', '')
        dct['source']= request.POST.get('source', '')
        dct['difficulty']= int(request.POST.get('difficulty', 0))
        dct['type']= request.POST.get('type', '')
        dct['creator']=request.POST.get('creator', '')
        dct['defunct']=request.POST.get('defunct', 'N')
        dct['accepted']=0
        dct['submit']=0
        dct['solved']=0
        contestInfo=request.POST.get('contests', None)
        dct['in_date'] = datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S')
    if all([dct['title'],dct['time_limit'],dct['memory_limit'],dct['description']]):
        if problem_id:
            Problem.objects.filter(problem_id=problem_id).update(**dct)
        else:
            insertRes=Problem.objects.create(**dct)
            problem_id=insertRes.problem_id
        if  testIn!=None and  testIn!=None:
            test_create(problem_id,'test.in',testIn)
            test_create(problem_id, 'test.out', testOut)
        test_create(problem_id, 'sample.input', dct['sample_input'])
        test_create(problem_id, 'sample.output', dct['sample_output'])
        if contestInfo!=None:
            temp = re.findall("(\d+)", contestInfo)  # 修改/新增关卡题目
            filter(None, temp)
            if temp != []:
                for contest_id in temp:
                    num=ContestProblem.objects.filter(contest_id=int(contest_id)).count()
                    ContestProblem.objects.create(contest_id=int(contest_id),problem_id=int(problem_id),num=num)
        return JsonResponse({'addPass':problem_id,'message':'true'},safe=False)
    else:
        return JsonResponse({'addError': 'lose something'}, safe=False)

#管理员修改密码
def adminResetPwd(request):
    if request.method == 'POST':
        admin = request.POST.get('admin')
        user_id = request.POST.get('user_id')
        new_pwd = request.POST.get('new_pwd')
        qr_pwd = request.POST.get('qr_pwd')
    if verifyPrivilege(admin)[0][0] == 1 or verifyPrivilege(admin)[0][0] == 0:
        if qr_pwd == new_pwd:
            user = Users.objects.filter(user_id = user_id).first()
            new_pwd = reg_pass(new_pwd)
            user.password = new_pwd
            user.save()
            massage = {'err':'Modification succeeded'}
        else:
            massage = {'err':'Password error'}
    else:
        massage = {'err':'Insufficient authority'}
    return JsonResponse(massage,safe=False)

#管理员权限列表
def privilegeList(request):
    if request.method == 'POST':
        admin = request.POST.get('admin')
        page = int(request.POST.get('page','1'))
        content = request.POST.get('content','')
    if verifyPrivilege(admin)[0][0] == 1 or verifyPrivilege(admin)[0][0] == 0:
        if content:
            privilege = getPrivilege(page,content)
            total = Privilege.objects.filter(Q(user_id__contains=content) | Q(rightstr__contains=content)).count()
            rs = {'total':total,'privilege':privilege}
            return JsonResponse(rs, safe=False)
        else:
            page1 = (page-1)*50
            page2 = page*50
            rightstrList = getRightStrList(page1, page2)
            with connection.cursor() as cursor:
                cursor.execute(
                    "SELECT * FROM privilege WHERE rightstr IN ('administrator','admin','source_browser','contest_creator','http_judge','problem_editor','password_setter','printer','balloon') ORDER BY user_id, rightstr")
                solution_data = cursor.fetchall()
            returnData = list(solution_data)
            total = len(returnData)
            rightstrList_data = []
            for data in rightstrList:
                rightstrList_data.append(
                    {
                        'user_id':data[0],
                        'rightstr':data[1],
                        'defunct':data[2]
                    }
                )
            rs = {'total':total,'rightsteList':rightstrList_data}
            return JsonResponse(rs, safe=False)
    else:
        massage = {'err': 'Insufficient authority'}
        return JsonResponse(massage, safe=False)

#删除权限
def deletePrivilage(request):
    if request.method == 'POST':
        admin = request.POST.get('admin')
        if not (verifyPrivilege(admin)[0][0] == 1 or verifyPrivilege(admin)[0][0] == 0):
            massage = {'err': 'Insufficient authority'}
            return JsonResponse(massage, safe=False)
        user_id = request.POST.get('user_id', '')
        rightstr = request.POST.get('rightstr', '')
    Privilege.objects.filter(user_id=user_id,rightstr=rightstr).delete()
    massage = {'err':'Delete succeeded'}
    return JsonResponse(massage, safe=False)

#权限修改
def modifyPrivilage(request):
    if request.method == 'POST':
        admin = request.POST.get('admin')
        if not (verifyPrivilege(admin)[0][0] == 1 or verifyPrivilege(admin)[0][0] == 0):
            massage = {'err': 'Insufficient authority'}
            return JsonResponse(massage, safe=False)
        user_id = request.POST.get('user_id', '')
        rightstr = request.POST.get('rightstr', '')
        defunct = request.POST.get('defunct')
    if defunct:
        if defunct == 'N':
            defunct = 'Y'
        else:
            defunct = 'N'
        Privilege.objects.filter(user_id=user_id,rightstr=rightstr).update(defunct = defunct)
        massage = {'err': 'modify succeeded'}
    else:
        massage = {'err': 'False'}
    return JsonResponse(massage, safe=False)

#班级管理
def classManage(request):
    if request.method == 'GET':
        admin = request.GET.get('admin')
        if not (verifyPrivilege(admin)[0][0] == 1 or verifyPrivilege(admin)[0][0] == 0):
            massage = {'err': 'Insufficient authority'}
            return JsonResponse(massage, safe=False)
        page = int(request.GET.get('page','1'))
        content = request.GET.get('content','')
    total = Class.objects.filter(Q(class_id__contains=content) | Q(class_name__contains=content)).count()
    class_list = Class.objects.filter(Q(class_id__contains=content) | Q(class_name__contains=content)).order_by('class_id')[(page-1)*50:page*50]
    class_list = changeToJson(class_list)
    rs = {'total':total,'class_list':class_list}
    return JsonResponse(rs, safe=False)

#删除班级
def classDelete(request):
    if request.method == 'POST':
        admin = request.POST.get('admin')
        if not (verifyPrivilege(admin)[0][0] == 1 or verifyPrivilege(admin)[0][0] == 0):
            massage = {'err': 'Insufficient authority'}
            return JsonResponse(massage, safe=False)
        class_id = request.POST.get('class_id')
        Class.objects.filter(class_id=class_id).delete()
        UserClass.objects.filter(class_id=class_id).delete()
        massage = {'err':'ture'}
        return JsonResponse(massage, safe=False)

#添加班级
def addClass(request):
    if request.method == 'POST':
        admin = request.POST.get('admin')
        if not (verifyPrivilege(admin)[0][0] == 1 or verifyPrivilege(admin)[0][0] == 0):
            massage = {'err': 'Insufficient authority'}
            return JsonResponse(massage, safe=False)
        class_name = request.POST.get('class_name','')
        college = request.POST.get('college')
        teacher = request.POST.get('teacher')
        team = request.POST.get('team')
        if not(class_name and college and team):
            massage = {'err':'Incomplete information'}
            return JsonResponse(massage, safe=False)
    if not teacher:
        teacher = admin
    team = team.split()
    Class.objects.create(class_name=class_name, college=college, teacher=teacher, class_score=0, creator=admin,team = 0)
    class_id = Class.objects.filter(class_name = class_name).first()
    class_id = class_id.class_id
    for data in team:
        UserClass.objects.create(class_id=class_id, user_id=data)
    massage = {'err':'success'}
    return JsonResponse(massage, safe=False)

#修改班级
def editClass(request):
    if request.method == 'POST':
        admin = request.POST.get('admin')
        if not (verifyPrivilege(admin)[0][0] == 1 or verifyPrivilege(admin)[0][0] == 0):
            massage = {'err': 'Insufficient authority'}
            return JsonResponse(massage, safe=False)
        class_id = request.POST.get('class_id')
        class_data = Class.objects.filter(class_id=class_id).first()
        class_name = request.POST.get('class_name')
        college = request.POST.get('college')
        teacher = request.POST.get('teacher')
        team = request.POST.get('team')
        if class_name:
            class_data.class_name = class_name
            class_data.save()
        if college:
            class_data.college = college
            class_data.save()
        if teacher:
            class_data.teacher = teacher
            class_data.save()
        if team:
            team = team.split()
            UserClass.objects.filter(class_id=class_id).delete()
            for data in team:
                UserClass.objects.create(class_id=class_id, user_id=data)
        massage = {'err': 'edit success'}
        return JsonResponse(massage, safe=False)
    elif request.method == 'GET':
        class_id = request.GET.get('class_id')
        class_data = Class.objects.filter(class_id=class_id).first()
        class_datas = []
        class_datas.append(
            {
                'class_id': class_data.class_id,
                'class_name': class_data.class_name,
                'college': class_data.college,
                'teacher': class_data.teacher
            }
        )
        user_data = UserClass.objects.filter(class_id=class_id).values('user_id')
        user_datas = ''
        for data in user_data:
            user_datas = user_datas + data['user_id'] + '\n'
        rs = {'class_datas': class_datas, 'user_data': user_datas}
        return JsonResponse(rs, safe=False)


#管理员问题列表
def adminProblemList(request):
    cpage = int(request.GET.get('cpage', '1'))
    content = request.GET.get('content', '')
    if request.method == 'POST':
        admin = request.POST.get('admin')
        if not (verifyPrivilege(admin)[0][0] == 1 or verifyPrivilege(admin)[0][0] == 0 or JudgmentAuthority(admin,'problem_editor')):
            massage = {'err': 'Insufficient authority'}
            return JsonResponse(massage, safe=False)
    statusId=request.POST.get('statusId',None)
    defunct = request.POST.get('defunct', None)
    deleteId=request.POST.get('deleteId',None)
    editId=request.POST.get('editId',None)
    source=request.POST.get('source',None)
    type=request.POST.get('type',None)
    difficulty=request.POST.get('difficulty',None)
    if editId!=None:
        Problem.objects.filter(problem_id=editId).update(source=source,type=type,difficulty=difficulty)
        return JsonResponse("editPass", safe=False)
    if deleteId!=None:
        try:
            Problem.objects.filter(problem_id=deleteId).delete()
        except:
            return JsonResponse("The problem doesn't exist", safe=False)
        return JsonResponse("deletePass", safe=False)
    if statusId!=None and defunct!=None:
        Problem.objects.filter(problem_id=statusId).update(defunct=defunct)
        return JsonResponse("editPass", safe=False)
    problemInfos=[]
    total = Problem.objects.filter(Q(problem_id__contains=content) | Q(source__contains=content) | Q(type__contains=content) | Q(title__contains=content)).count()
    problemInfo=Problem.objects.filter(Q(problem_id__contains=content) | Q(source__contains=content) | Q(type__contains=content) | Q(title__contains=content)).order_by('-problem_id')[(cpage-1)*50:cpage*50]
    for data in problemInfo:
        if data.defunct=="N":
            data.defunct="Available"
        elif data.defunct=="Y":
            data.defunct = "Reserved"
        problemInfos.append(model_to_dict(data))
    proAll = total
    allPage = proAll / 50
    if isinstance(allPage, int):
        proAll = allPage
    else:
        proAll = int(allPage) + 1
    return JsonResponse({'problemInfos':problemInfos,'allPage':proAll,'total':total,'cpage':cpage}, safe=False)

#管理员问题列表 测试数据testData
def testData(request):
    if request.method == 'POST':
        admin = request.POST.get('admin')
        if not (verifyPrivilege(admin)[0][0] == 1 or verifyPrivilege(admin)[0][0] == 0 or JudgmentAuthority(admin,'problem_editor')):
            massage = {'err': 'Insufficient authority'}
            return JsonResponse(massage, safe=False)
    if request.method == 'GET':
        problem_id=request.GET.get('problem_id')
        infos=list_read(problem_id)
        for data in infos:
            dt=datetime.datetime.fromtimestamp(data['createTime'])
            data['createTime']=dt.strftime("%Y-%m-%d %H:%M:%S")
        return JsonResponse({'fileInfos':infos}, safe=False)
    if request.method == 'POST':
        problem_id = request.POST.get('problem_id')
        delete = request.POST.get('deleteFileName',None)
        name = request.POST.get('oldname',None)
        rename= request.POST.get('rename',None)
        edit = request.POST.get('editFileName', None)
        create = request.POST.get('createFileName', None)
        down=request.POST.get('downFileName', None)
        msg=request.POST.get('msg', None)   #新建or修改测试用例的内容

    if delete!=None:
        msg=file_delete(problem_id,delete)
        return JsonResponse(msg, safe=False)
    if name!=None and rename!=None:
        msg = file_rename(problem_id, name,rename)
        return JsonResponse(msg, safe=False)
    if edit!=None:
        msg = test_read(problem_id, edit)  #返回待编辑内容
        return JsonResponse(msg, safe=False)
    if create!=None and msg!=None:
        test_create(problem_id, create, msg)
        return JsonResponse('createPass', safe=False)
    if down!=None:
        file=test_down(problem_id, down)
        return file


#管理员问题列表 添加测试数据 testData
def addTestData(request):
    if request.method == 'POST':
        admin = request.POST.get('admin')
        if not (verifyPrivilege(admin)[0][0] == 1 or verifyPrivilege(admin)[0][0] == 0 or JudgmentAuthority(admin,'problem_editor')):
            massage = {'err': 'Insufficient authority'}
            return JsonResponse(massage, safe=False)
    if request.method == 'POST':
        problem_id = request.POST.get('problem_id',None)
        files =request.FILES.get('tests','')
    if files:


            data_path = "..//..//judge//data//%s//" % problem_id  # 新创建的txt文件的存放路径


            #full_path = data_path + f.name[:-1]  # 也可以创建一个.doc的word文档
            full_path = data_path
        #    file = open(full_path, 'wb+')



            file = open(os.path.join(data_path, files.name), 'wb+')

            for chunk in files.chunks():
                file.write(chunk)
            file.close()
    else:
        return JsonResponse('file is null', safe=False)
    if problem_id==None:
        return JsonResponse('problem_id is null', safe=False)
    return JsonResponse('createPass', safe=False)

#管理员限制登录ip
def setLoginIp(request):
    if request.method == 'POST':
        admin = request.POST.get('admin')
        if not (verifyPrivilege(admin)[0][0] == 1 or verifyPrivilege(admin)[0][0] == 0):
            massage = {'err': 'Insufficient authority'}
            return JsonResponse(massage, safe=False)
    if request.method == 'POST':
        userStr = request.POST.get('addUsers', None)
        hour=request.POST.get('hour', None)
        deleteUsers = request.POST.get('deleteUsers', None)
        class_id = request.POST.get('class_id', None)
        if deleteUsers!=None:
            users = deleteUsers.split(r'\n')
            for user in users:
                UserIp.objects.filter(user_id=user).delete()
                #Loginlog.objects.filter(user_id=user).delete()
            return JsonResponse('deleteLoginLogPass', safe=False)
        if userStr != None:
            users=userStr.split(r'\n')
            time=datetime.datetime.now()
            for user in users:
                UserIp.objects.create(user_id=user,start_time=time,during=hour)
            return JsonResponse('setLoginLogPass', safe=False)

    if class_id!=None:
        userInfo = UserClass.objects.filter(class_id=class_id)
        usersStr = ''
        for dataUser in userInfo:
            if usersStr == '':
                usersStr = dataUser.user_id
            usersStr = usersStr + '\n' + dataUser.user_id
        return JsonResponse(usersStr, safe=False)
    classInfos=[]
    classInfo=Class.objects.filter()
    for data in classInfo:
        temp={}
        temp['class_id']=data.class_id
        temp['class_name']=data.class_name
        classInfos.append(temp)
    return JsonResponse(classInfos, safe=False)

#管理员竞赛界面
def contestList(request):
    if request.method == 'POST':
        admin = request.POST.get('admin')
        if not (verifyPrivilege(admin)[0][0] == 1 or verifyPrivilege(admin)[0][0] == 0 or JudgmentAuthority(admin, 'contest_creator')):
            massage = {'err': 'Insufficient authority'}
            return JsonResponse(massage, safe=False)
        content= request.POST.get('content','')
        page = int(request.POST.get('page','1'))
        contest = Contest.objects.filter(Q(contest_id__contains=content) | Q(title__contains=content)).all().order_by('-contest_id')[(page-1)*50:page*50]
        total = Contest.objects.filter(Q(contest_id__contains=content) | Q(title__contains=content)).count()
        contest = changeToJson(contest)
        rs = {'content':contest,'total':total}
        return JsonResponse(rs, safe=False)


#修改竞赛状态
def modifyContestStatus(request):
    if request.method == 'POST':
        contest_id = request.POST.get('content')
        admin = request.POST.get('admin')
        if not (verifyPrivilege(admin)[0][0] == 1 or verifyPrivilege(admin)[0][0] == 0 or JudgmentAuthority(admin, 'contest_creator')):
            massage = {'err': 'Insufficient authority'}
            return JsonResponse(massage, safe=False)
    contest = Contest.objects.filter(contest_id = contest_id).first()
    if contest.defunct == 'N':
        contest.defunct = 'Y'
        contest.save()
    else:
        contest.defunct = 'N'
        contest.save()
    massage = {'err':'modification succeeded'}
    return JsonResponse(massage, safe=False)

#修改竞赛类型
def changeContestType(request):
    if request.method == 'POST':
        contest_id = request.POST.get('content')
    contest = Contest.objects.filter(contest_id = contest_id).first()
    if contest.private == 0:
        contest.private =1
        contest.save()
    elif contest.private == 1:
        contest.private = 0
        contest.save()
    massage = {'err': 'modification succeeded'}
    return JsonResponse(massage, safe=False)


def addContest(request):
    if request.method == 'POST':
        admin = request.POST.get('admin')
        if not (verifyPrivilege(admin)[0][0] == 1 or verifyPrivilege(admin)[0][0] == 0 or JudgmentAuthority(admin, 'contest_creator')):
            massage = {'err': 'Insufficient authority'}
            return JsonResponse(massage, safe=False)
        title = request.POST.get('title')
        start_time = request.POST.get('start_time')
        start_time = datetime.datetime.strptime(start_time, "%Y-%m-%d %H:%M:%S")
        end_time = request.POST.get('end_time')
        end_time = datetime.datetime.strptime(end_time, "%Y-%m-%d %H:%M:%S")
        problem = request.POST.get('problem')
        description = request.POST.get('description')
        private = request.POST.get('private')
        password = request.POST.get('password', '')
        creator = request.POST.get('creator')
        lang = request.POST.get('lang','')
        team = request.POST.get('team')
        class_name = request.POST.get('class_name')
        contest_type = int(request.POST.get('contest_type'))
        if not(title and start_time and end_time and problem and description and private and creator):
            massage = {'err':'Incomplete information'}
            return JsonResponse(massage, safe=False)
        if class_name:
            user_data = []
            class_id = Class.objects.filter(class_name = class_name).first()
            class_id = class_id.class_id
            users = UserClass.objects.filter(class_id = class_id).values('user_id')
            for user in users:
                user = user['user_id']
                user_data.append(user)
                return JsonResponse(user_data, safe=False)

        else:
            if lang:
                langmask = 0
                for data in lang:
                    langmask += 1<<data
                language_ext =["c", "cc", "pas", "java", "rb", "sh", "py", "php", "pl", "cs", "m", "bas", "scm","c", "cc", "lua", "js", "go"]
                langmask = ((1 << len(language_ext)) - 1)&(~langmask)
            else:
                langmask = 0
            contest = Contest.objects.create(title=title, start_time=start_time, end_time=end_time, description=description, private=private, creator=creator, password=password, langmask = langmask,defunct = 'N')
            problem = problem.split('，')
            content_id_new = str(contest.contest_id)
            for data in problem:
                problem = Problem.objects.filter(problem_id = data).first()
                if problem:
                    num = 0
                    ContestProblem.objects.create(problem_id = data, contest_id=contest.contest_id, num=num)
                    num +=1
            if team:
                team = team.split()
                for data in team:
                    contest_name = 'c' + content_id_new
                    Privilege.objects.create(user_id=data, rightstr=contest_name, defunct='N')
            contest.start_time = contest.start_time.strftime("%Y-%m-%d %H:%M:%S")
            contest.end_time = contest.end_time.strftime("%Y-%m-%d %H:%M:%S")
            if not contest_type:
                massage = {'err': 'ture'}
                return JsonResponse(massage, safe=False)
            elif contest_type == 1:
                content ='<p>'+contest.title+'个人赛将于:'+ contest.start_time +'至:'+contest.end_time+'在金职院东实训楼举办,请各位参赛选手提前入场.</p><br/>'+ contest.description
                content = {'content': content, 'contest_type': 1, 'contest_id': contest.contest_id}
                content = str(content)
            elif contest_type == 2:
                content = '<p>'+contest.title+'团队赛将于:'+ contest.start_time +'至:'+contest.end_time+'在金职院东实训楼举办,请各位参赛选手提前入场.</p><br/>'+ contest.description +'\n'
                content = {'content': content, 'contest_type': 2, 'contest_id': contest.contest_id}
                content = str(content)
            title = contest.title + '通知暨报名入口'
            time_n = datetime.datetime.now()
            News.objects.create(
                user_id=creator,
                title=title,
                content=content,
                image=0,
                image_path=0,
                importance=0,
                time=time_n,
                defunct='N'
            )
            massage = {'err':'ture'}
            return JsonResponse(massage, safe=False)
    elif request.method == 'GET':
        class_data = []
        class_name = Class.objects.all().values('class_name')
        for data in class_name:
            class_datas = data['class_name']
            class_data.append(class_datas)
        language = ["C", "C++", "Pascal", "Java", "Ruby", "Bash", "Python", "PHP","Perl", "C#","Obj-C","FreeBasic","Scheme","Clang","Clang++","Lua","JavaScript","Go"]
        rs = {'language':language,'class_data':class_data}
        return JsonResponse(rs, safe=False)

#修改竞赛
def changeContest(request):
    if request.method == 'POST':
        admin = request.POST.get('admin')
        if not (verifyPrivilege(admin)[0][0] == 1 or verifyPrivilege(admin)[0][0] == 0 or JudgmentAuthority(admin, 'contest_creator')):
            massage = {'err': 'Insufficient authority'}
            return JsonResponse(massage, safe=False)
        contest_id = request.POST.get('contest_id')
        contest = Contest.objects.filter(contest_id=contest_id).first()
        title = request.POST.get('title')
        start_time = request.POST.get('start_time')
        start_time = datetime.datetime.strptime(start_time, "%Y-%m-%d %H:%M:%S")
        end_time = request.POST.get('end_time')
        end_time = datetime.datetime.strptime(end_time, "%Y-%m-%d %H:%M:%S")
        problem = request.POST.get('problem')
        description = request.POST.get('description')
        private = request.POST.get('private')
        password = request.POST.get('password', '')
        creator = request.POST.get('creator')
        lang = request.POST.get('lang','')
        team = request.POST.get('team')
        class_name = request.POST.get('class_name')
        if not (title and start_time and end_time and problem and description and private and creator):
            massage = {'err': 'Incomplete information'}
            return JsonResponse(massage, safe=False)
        if class_name:
            user_data = []
            class_id = Class.objects.filter(class_name=class_name).first()
            class_id = class_id.class_id
            users = UserClass.objects.filter(class_id=class_id).values('user_id')
            for user in users:
                user = user['user_id']
                user_data.append(user)
                return JsonResponse(user_data, safe=False)
        else:
            if lang:
                langmask = 0
                for data in lang:
                    langmask += 1 << data
                language_ext = ["c", "cc", "pas", "java", "rb", "sh", "py", "php", "pl", "cs", "m", "bas", "scm", "c",
                                "cc", "lua", "js", "go"]
                langmask = ((1 << len(language_ext)) - 1) & (~langmask)
            else:
                langmask = 0
            if contest:
                contest.title = title
                contest.start_time = start_time
                contest.end_time = end_time
                contest.description = description
                contest.private = private
                contest.creator = creator
                contest.password = password
                contest.langmask = langmask
                contest.save()
            problem = problem.split('，')
            contest = Contest.objects.filter(title=title).first()
            content_id_new = str(contest.contest_id)
            ContestProblem.objects.filter(contest_id=contest.contest_id).delete()
            for data in problem:
                num = 0
                ContestProblem.objects.create(problem_id=data, contest_id=contest.contest_id, num=num)
                num += 1
            if team:
                contest_name = 'c' + content_id_new
                Privilege.objects.filter(rightstr=contest_name).delete()
                team = team.split()
                for data in team:
                    Privilege.objects.create(user_id=data, rightstr=contest_name, defunct='N')
            massage = {'err': 'ture'}
            return JsonResponse(massage, safe=False)
    elif request.method == 'GET':
        contest_id = request.GET.get('contest_id')
        contest = Contest.objects.filter(contest_id=contest_id).all()
        contest = changeToJson(contest)
        class_data = []
        class_name = Class.objects.all().values('class_name')
        contest_problem = ContestProblem.objects.filter(contest_id = contest_id).values('problem_id')
        pdatas = ''
        for pdata in contest_problem:
            pdata = str(pdata['problem_id'])
            if pdatas == '':
                pdatas = pdatas + pdata
            else:
                pdatas = pdatas + '，' + pdata
        contest_name = 'c' + contest_id
        user_ids = Privilege.objects.filter(rightstr=contest_name).values('user_id')
        udatas = ''
        for udata in user_ids:
            udata = udata['user_id']
            if udata:
                udatas = udatas + udata +'\n'
        for data in class_name:
            class_datas = data['class_name']
            class_data.append(class_datas)
        language = ["C", "C++", "Pascal", "Java", "Ruby", "Bash", "Python", "PHP", "Perl", "C#", "Obj-C", "FreeBasic",
                    "Scheme", "Clang", "Clang++", "Lua", "JavaScript", "Go"]
        rs = {'language': language, 'class_data': class_data, 'contest': contest,'user_id':udatas,'pid':pdatas}
        return JsonResponse(rs, safe=False)


#删除竞赛
def deleteContest(request):
    if request.method == 'POST':
        admin = request.POST.get('admin')
        if not (verifyPrivilege(admin)[0][0] == 1 or verifyPrivilege(admin)[0][0] == 0 or JudgmentAuthority(admin, 'contest_creator')):
            massage = {'err': 'Insufficient authority'}
            return JsonResponse(massage, safe=False)
        contest_id  = request.POST.get('contest_id')
        contest_name = 'c' + str(contest_id)
        Privilege.objects.filter(rightstr=contest_name).delete()
        Contest.objects.filter(contest_id =contest_id).delete()
        contest = Contest.objects.filter(contest_id =contest_id).first()
        if contest:
            massage = {'err':'False'}
        else:
            massage = {'err':'True'}
        return JsonResponse(massage, safe=False)


#比赛账号生成器
def accountGenerator(request):
    if request.method == 'POST':
        admin = request.POST.get('admin')
        if not (verifyPrivilege(admin)[0][0] == 1 or verifyPrivilege(admin)[0][0] == 0 or JudgmentAuthority(admin, 'contest_creator')):
            massage = {'err': 'Insufficient authority'}
            return JsonResponse(massage, safe=False)
        prefix = request.POST.get('prefix','team')
        contestId = request.POST.get('contestId','')
        teams = request.POST.get('teams',5)
        user = request.POST.get('user')
        if user:
            user = user.split()
        teams_data = []
        for i in range(1,int(teams)+1):
            print(i)
            login_id = prefix + timeChange(i)
            password = ''.join(random.sample(string.ascii_letters + string.digits, 10))
            md5 = hashlib.md5()
            md5.update(password.encode(encoding='utf-8'))
            en_password = md5.hexdigest()
            en_password = reg_pass(en_password)
            if user:
                user_num = len(user)
                if user_num >= i:
                    user_nick = user[i-1]
                else:
                    user_nick = 'your_own_nick'
            else:
                user_nick = 'your_own_nick'
            users = Users.objects.filter(user_id = login_id).first()
            if not users:
                Users.objects.create(
                   user_id=login_id,
                   email='your_own_email@internet',
                   reg_time=time.strftime("%Y-%m-%d %H:%M:%S", time.localtime(time.time())),
                   nick=user_nick,
                   school='your_own_school',
                   real_name='real_name',
                   ip=pub.get_ip(request),
                   volume=1,
                   language=1,
                   score=0,
                   submit=0,
                   solved=0,
                   defunct='N',
                   password=en_password
                )
            else:
                users.password = en_password
                users.nick = user_nick
            if contestId:
                contestId = 'c'+contestId
                Privilege.objects.create(user_id = login_id, rightstr = contestId, defunct = 'N')
                contestId = contestId[1:]
            teams_data.append(
                {
                    'login_id':login_id,
                    'password':password,
                    'nick':user_nick
                }
            )
        return JsonResponse(teams_data, safe=False)

#添加权限
def addPrivilege(request):
    if request.method == 'POST':
        admin = request.POST.get('admin')
        if not (verifyPrivilege(admin)[0][0] == 1 or verifyPrivilege(admin)[0][0] == 0):
            massage = {'err': 'Insufficient authority'}
            return JsonResponse(massage, safe=False)
        user = request.POST.get('user')
        privilege = request.POST.get('privilege')
        contest = request.POST.get('contest')
        problem = request.POST.get('problem')
        if privilege:
            Privilege.objects.create(user_id = user, rightstr = privilege, defunct = 'N')
            massage = {'err': 'privilegeSuccessfully added'}
            return JsonResponse(massage, safe=False)
        elif contest:
            contest = 'c' + contest
            Privilege.objects.create(user_id=user, rightstr=contest, defunct='N')
            massage = {'err': 'contestSuccessfully added'}
            return JsonResponse(massage, safe=False)
        elif problem:
            problem = 'p' + problem
            Privilege.objects.create(user_id=user, rightstr=problem, defunct='N')
            massage = {'err': 'problemSuccessfully added'}
            return JsonResponse(massage, safe=False)
        massage = {'err':'Incomplete information input'}
        return JsonResponse(massage, safe=False)

#管理员题解列表
def problemSolutionList(request):
    if request.method == 'POST':
        admin = request.POST.get('admin')
        if not (verifyPrivilege(admin)[0][0] == 1 or verifyPrivilege(admin)[0][0] == 0 or JudgmentAuthority(admin,'problem_solution')):
            massage = {'err': 'Insufficient authority'}
            return JsonResponse(massage, safe=False)
        page = int(request.POST.get('page','1'))
        content = request.POST.get('content','')
    total = Topic.objects.filter(Q(topic_id__contains=content) | Q(pid__contains=content)).count()
    topic = Topic.objects.filter(Q(topic_id__contains=content) | Q(pid__contains=content)).all()[(page-1)*50:page*50]
    problemSolution_data = []
    for data in topic:
        if data.defunct == 'N':
            massage = 'approved'
        else:
            massage = 'under review'
        p_title = Problem.objects.filter(problem_id = data.pid).values('title')
        if p_title:
            p_title = p_title[0]
            p_title = p_title['title']
        else:

            p_title = ''
        problemSolution_data.append(
            {
                'topic_id':data.topic_id,
                'p_title':p_title,
                'pid':data.pid,
                'title': data.title.decode('utf-8'),
                'massage': massage,
                'content': data.content,
                'time': data.time,
                'author_id': data.author_id
            }
        )
    rs = {'total':total,'topic':problemSolution_data}
    return JsonResponse(rs, safe=False)

#修改题解状态
def modifySolutionList(request):
    if request.method == 'POST':
        admin = request.POST.get('admin')
        if not (verifyPrivilege(admin)[0][0] == 1 or verifyPrivilege(admin)[0][0] == 0 or JudgmentAuthority(admin,'problem_solution')):
            massage = {'err': 'Insufficient authority'}
            return JsonResponse(massage, safe=False)
        topic_id = request.POST.get('topic_id')
        topic = Topic.objects.filter(topic_id = topic_id).first()
        user = Users.objects.filter(user_id = topic.author_id).first()
        if topic.defunct == 'Y':
            topic.defunct = 'N'
            topic.save()
            user.score += 100
            user.save()
        elif topic.defunct == 'N':
            topic.defunct = 'Y'
            topic.save()
            user.score -= 100
            user.save()
        return JsonResponse('ture', safe=False)

# 管理员 更改问题ID
def problemChangeId(request):
    if request.method == 'POST':
        admin = request.POST.get('admin')
        if not (verifyPrivilege(admin)[0][0] == 1 or verifyPrivilege(admin)[0][0] == 0 or JudgmentAuthority(admin, 'problem_editor')):
            massage = {'err': 'Insufficient authority'}
            return JsonResponse(massage, safe=False)
    if request.method == 'POST':
        oldProblem_id = request.POST.get('oldProblem_id')
        newProblem_id = request.POST.get('newProblem_id')
        c = connection.cursor()  # 原生sql
        sql = 'update problem set problem_id=%s where problem_id=%s' % (newProblem_id, oldProblem_id)
        if c.execute(sql):
            c.close()
            return JsonResponse('Pass', safe=False)
        else:
            c.close()
            return JsonResponse(sql, safe=False)

# 管理员导入问题  excel文件
def importProblemE(request):
    if request.method == 'POST':
        admin = request.POST.get('admin')
        if not (verifyPrivilege(admin)[0][0] == 1 or verifyPrivilege(admin)[0][0] == 0):
            massage = {'err': 'Insufficient authority'}
            return JsonResponse(massage, safe=False)
    excel_raw_data = pd.read_excel(request.FILES.get('file', ''), header=None)
    # 删除第一行的标题
    excel_raw_data.drop([0, 0], inplace=True)
    # 获取每列
    accepted = excel_raw_data.iloc[:, [0]]
    creator  = excel_raw_data.iloc[:, [1]]
    defunct  = excel_raw_data.iloc[:, [2]]
    description = excel_raw_data.iloc[:, [3]]
    difficulty  = excel_raw_data.iloc[:, [4]]
    hint  = excel_raw_data.iloc[:, [5]]
    #in_date = excel_raw_data.iloc[:, [6]]
    input  = excel_raw_data.iloc[:, [7]]
    memory_limit  = excel_raw_data.iloc[:, [8]]
    output  = excel_raw_data.iloc[:, [9]]
    #problem_id = excel_raw_data.iloc[:, [10]]
    sample_input  = excel_raw_data.iloc[:, [11]]
    sample_output  = excel_raw_data.iloc[:, [12]]
    solved  = excel_raw_data.iloc[:, [13]]
    source  = excel_raw_data.iloc[:, [14]]
    spj  = excel_raw_data.iloc[:, [15]]
    submit= excel_raw_data.iloc[:, [16]]
    time_limit= excel_raw_data.iloc[:, [17]]
    title= excel_raw_data.iloc[:, [18]]
    type= excel_raw_data.iloc[:, [19]]
    # 对每一列数据进行处理，从DataFrame类型转换为list类型
    defunct_list=defunct.values.tolist()
    solved_list=solved.values.tolist()
    submit_list=submit.values.tolist()
    accepted_list=accepted.values.tolist()
    title_list = title.values.tolist()
    time_limit_list = time_limit.values.tolist()
    memory_limit_list = memory_limit.values.tolist()
    description_list = description.values.tolist()
    input_list = input.values.tolist()
    output_list = output.values.tolist()
    sample_input_list = sample_input.values.tolist()
    sample_output_list = sample_output.values.tolist()
    #testIn_list = testIn.values.tolist()
    #testOut_list = testOut.values.tolist()
    hint_list = hint.values.tolist()
    spj_list = spj.values.tolist()
    source_list = source.values.tolist()
    difficulty_list = difficulty.values.tolist()
    type_list = type.values.tolist()
    creator_list = creator.values.tolist()
    problem_id_list = []
    # 对每一列的每一行的数据进行转换，转换为相应类型，保存在数据库中
    for i in range(len(title_list)):
        dct = {}
        dct['title'] = str(title_list[i][0])
        dct['time_limit'] = int(str(time_limit_list[i][0]))
        dct['memory_limit'] = int(str(memory_limit_list[i][0]))
        dct['description'] = str(description_list[i][0])
        dct['input'] = str(input_list[i][0])
        dct['output'] = str(output_list[i][0])
        dct['sample_input'] = str(sample_input_list[i][0])
        dct['sample_output'] = str(sample_output_list[i][0])
        #testIn = testIn_list[i][0]
        #testOut = testOut_list[i][0]
        dct['spj'] = int(str(spj_list[i][0]))
        dct['hint'] = str(hint_list[i][0])
        dct['source'] = str(source_list[i][0])
        dct['difficulty'] = int(str(difficulty_list[i][0]))
        dct['type'] = str(type_list[i][0])
        dct['creator'] = str(creator_list[i][0])
        dct['defunct'] = str(defunct_list[i][0])
        dct['accepted'] = int(str(accepted_list[i][0]))
        dct['submit'] = int(str(submit_list[i][0]))
        dct['solved'] = int(str(solved_list[i][0]))
        dct['in_date'] = datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S')
        if all([dct['title'], dct['time_limit'], dct['memory_limit'], dct['description'], dct['input'],
                dct['output'], dct['sample_input'], dct['sample_output']]):
            insertRes = Problem.objects.create(**dct)
            problem_id = insertRes.problem_id
            #if testIn != None and testIn != None:
            #    test_create(problem_id, 'test.in', testIn)
            #    test_create(problem_id, 'test.out', testOut)
            test_create(problem_id, 'sample.input', dct['sample_input'])
            test_create(problem_id, 'sample.out', dct['sample_output'])
        problem_id_list.append(problem_id)
    return JsonResponse({'addPass': problem_id_list}, safe=False)

# 管理员导出问题excel
def exportProblemE(request):
    if request.method == 'POST':
        admin = request.POST.get('admin')
        if not (verifyPrivilege(admin)[0][0] == 1 or verifyPrivilege(admin)[0][0] == 0):
            massage = {'err': 'Insufficient authority'}
            return JsonResponse(massage, safe=False)
    start_id = request.POST.get('start_id')
    end_id = request.POST.get('end_id')
    outfile = BytesIO()
    orderser = Problem.objects.filter(problem_id__gt=start_id, problem_id__lt=end_id)
    appos = orderser.values()  # 这里可以格式化当前表和关联表的数据
    orders = pd.DataFrame(appos)
    response = HttpResponse(content_type='application/vnd.ms-excel')
    #response.write(codecs.BOM_UTF8)
    excel_name = 'problemList'+datetime.datetime.now().strftime('%Y%m%d%H%M%S')+'.xlsx'
    response['Content-Disposition'] = 'attachment;filename="%s"' % excel_name
    orders.to_excel(outfile, index=False)
    response.write(outfile.getvalue())
    return response


# 管理员导入问题  xml文件
def importProblemX(request):
    if request.method == 'POST':
        admin = request.POST.get('admin')
        if not (verifyPrivilege(admin)[0][0] == 1 or verifyPrivilege(admin)[0][0] == 0):
            massage = {'err': 'Insufficient authority'}
            return JsonResponse(massage, safe=False)

    #content = minidom.parse(request.FILES.get('file', '')).toxml('utf-8') #类型为bytes
    #xml_text=bytes.decode(content)
    #tree = ET.fromstring(xml_text)
    tree = ET.parse(request.FILES.get('file', ''))
    xml_row_nodes=tree.findall("./item")
    dcts = []
    # 对每一列的每一行的数据进行转换，转换为相应类型，保存在数据库中
    for i in xml_row_nodes:
        dct = {}
        dct['title'] = i.find("title").text
        dct['description'] =i.find("description").text
        dct['input'] =i.find("input").text
        dct['output'] =i.find("output").text
        dct['sample_input'] =i.find("sample_input").text
        dct['sample_output'] =i.find("sample_output").text
        dct['hint'] =i.find("hint").text
        dct['source'] =i.find("source").text
        dct['difficulty'] =0
        dct['type'] =None
        dct['creator'] =None
        dct['defunct'] ='N'
        dct['time_limit'] = int(i.find("time_limit").text)
        dct['memory_limit'] = int(i.find("memory_limit").text)
        dct['spj'] =0
        dct['accepted'] = 0
        dct['submit'] = 0
        dct['solved'] = 0
        dct['in_date'] = datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S')
        if all([dct['title'], dct['time_limit'], dct['memory_limit'], dct['description'], dct['input'],
                dct['output'], dct['sample_input'], dct['sample_output']]):
            insertRes = Problem.objects.create(**dct)
            problem_id = insertRes.problem_id
            test_create(problem_id, 'sample.input', dct['sample_input'])
            test_create(problem_id, 'sample.out', dct['sample_output'])
        inputs=i.findall("test_input")
        couts=0
        for j in inputs:
            test_create(problem_id, 'test%d.in'%couts, j.text)
            couts+=1
        outputs = i.findall("test_output")
        couts = 0
        for j in outputs:
            test_create(problem_id, 'test%d.out'%couts, j.text)
            couts+=1
        solutions = i.findall("solution")
        solutionDict={}
        language_name = ["C", "C++", "Pascal", "Java", "Ruby", "Bash", "Python", "PHP", "Perl", "C#", "Obj-C",
                         "FreeBasic", "Scheme", "Clang", "Clang++", "Lua", "JavaScript", "Go", "Other Language"]
        for j in solutions:
            solutionDict['problem_id']=problem_id
            solutionDict['user_id'] =admin
            solutionDict['language'] = language_name.index(j.attrib['language'])
            solutionDict['ip'] = '127.0.0.1'
            solutionDict['contest_id'] = None
            solutionDict['num'] = -1
            solutionDict['code_length'] = len(j.text)
            solutionDict['valid'] = 1
            solutionDict['time'] = 0
            solutionDict['memory'] = 0
            solutionDict['result'] = 1
            solutionDict['pass_rate'] = 0.00
            solutionDict['lint_error'] = 0
            solutionDict['judger'] = 'LOCAL'
            solutionDict['in_date'] =dct['in_date']
            solutionDict['judgetime'] =dct['in_date']
            insertRes = Solution.objects.create(**solutionDict)
            solution_id = insertRes.solution_id
            det = {'solution_id': solution_id, 'source': j.text}
            SourceCodeUser.objects.create(**det)
            SourceCode.objects.create(**det)
        dcts.append(problem_id)
    #return HttpResponse(json.dumps({'addPass': dcts}, ensure_ascii=False), content_type='application/json')
    return JsonResponse({'addPass': dcts}, safe=False)

# 管理员导出问题xml


#报名管理
def signUpManage(request):
    if request.method == 'POST':
        admin = request.POST.get('admin')
        if not (verifyPrivilege(admin)[0][0] == 1 or verifyPrivilege(admin)[0][0] == 0):
            massage = {'err': 'Insufficient authority'}
            return JsonResponse(massage, safe=False)
        user1 = request.POST.get('user1')
        user2 = request.POST.get('user2')
        user3 = request.POST.get('user3')
        team = request.POST.get('team')
        contest_id = request.POST.get('contest_id')
        if not (user1 and user2 and user3):
            massage = {'err': 'False'}
            return JsonResponse(massage, safe=False)
        if not user1:
            user1 = 1
        if not user2:
            user2 = 1
        if not user3:
            user3 = 1
        if contest_id and team:
            Signup.objects.create(team = team,user1 = user1, user2=user2, user3=user3,contest_id = contest_id)
            for data in [user1,user2,user3]:
                if data != 1:
                    contest_id_name = 'c' + str(contest_id)
                    Privilege.objects.create(user_id=data, rightstr=contest_id_name, defunct='N')
        if not contest_id or not team:
            massage = {'err':'Incomplete information'}
        else:
            massage = {'err': 'ture'}
        return JsonResponse(massage, safe=False)
    if request.method == 'GET':
        content = request.GET.get('content','')
        page = int(request.GET.get('page','1'))
        signup = Signup.objects.filter(contest_id__contains = content).all()[(page-1)*50:page*50]
        total = Signup.objects.filter(contest_id__contains=content).count()
        signup_data = []
        contest = Contest.objects.all().order_by('-start_time')[0:10]
        contest = changeToJson(contest)
        for data in signup:
            contest_name = Contest.objects.filter(contest_id = data.contest_id).first()
            user1 = Users.objects.filter(user_id= data.user1).first()
            if user1:
                if user1.real_name:
                    user1_name = user1.real_name
                else:
                    user1_name = 'Not set'
            else:
                user1_name = 'Not set'
            user2= Users.objects.filter(user_id=data.user2).first()
            if user2:
                if user2.real_name:
                    user2_name = user2.real_name
                else:
                    user2_name = 'Not set'
            else:
                user2_name = 'Not set'
            user3 = Users.objects.filter(user_id=data.user3).first()
            if user3:
                if user3.real_name:
                    user3_name = user3.real_name
                else:
                    user3_name = 'Not set'
            else:
                user3_name = 'Not set'
            if not contest_name:
                title = '1'
            else:
                title = contest_name.title
            signup_data.append(
                {
                    'id':data.id,
                    'team':data.team,
                    'contest_id':data.contest_id,
                    'contest': title,
                    'user1':data.user1,
                    'user1_name':user1_name,
                    'user2': data.user2,
                    'user2_name': user2_name,
                    'user3': data.user3,
                    'user3_name': user3_name,
                }
            )
        rs = {'signup':signup_data,'total':total,'contest':contest}
        return JsonResponse(rs, safe=False)

#修改报名管理
def modifySignUpManage(request):
    if request.method == 'POST':
        admin = request.POST.get('admin')
        if not (verifyPrivilege(admin)[0][0] == 1 or verifyPrivilege(admin)[0][0] == 0):
            massage = {'err': 'Insufficient authority'}
            return JsonResponse(massage, safe=False)
        user1 = request.POST.get('user1')
        user2 = request.POST.get('user2')
        user3 = request.POST.get('user3')
        team = request.POST.get('team')
        id = request.POST.get('id')
        signup = Signup.objects.filter(id = id).first()
        if user1:
            signup.user1 = user1
            signup.save()
        if user2:
            signup.user2 = user2
            signup.save()
        if user3:
            signup.user3 = user3
            signup.save()
        if team:
            signup.team = team
            signup.save()
        return JsonResponse('true', safe=False)


#删除报名管理
def deleteSignUpManage(request):
    if request.method == 'POST':
        admin = request.POST.get('admin')
        if not (verifyPrivilege(admin)[0][0] == 1 or verifyPrivilege(admin)[0][0] == 0):
            massage = {'err': 'Insufficient authority'}
            return JsonResponse(massage, safe=False)
        id = request.POST.get('id')
        Signup.objects.filter(id=id).delete()
        return JsonResponse('true', safe=False)
#题目提交功能
def storeSolution(request):
    if request.method == 'POST':
        #solution_id=request.POST.get
        dct={}
        dct['problem_id'] = int(request.POST.get('problem_id'))
        dct['user_id'] = request.POST.get('user_id')
        dct['language'] = int(request.POST.get('language'))
        dct['ip'] = request.POST.get('ip')
        dct['contest_id'] = request.POST.get('contest_id',None)
        if dct['contest_id'] != None:
            dct['contest_id'] = int(dct['contest_id'])
        dct['num'] = int(request.POST.get('num', '-1'))
        dct['code_length'] = int(request.POST.get('code_length'))
        code = request.POST.get('code')
        dct['valid'] = int(request.POST.get('valid', '1'))
        dct['time'] = int(request.POST.get('time','0'))
        dct['memory'] = int(request.POST.get('memory','0'))
        #dct['in_date']= datetime.datetime.now()
        dct['in_date'] = datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S')
        dct['result'] =int(request.POST.get('result','14'))
        dct['judgetime']= request.POST.get('judgetime',"1999-01-01 00:00:00")
        dct['pass_rate']= decimal.Decimal(request.POST.get('pass_rate','0.00'))
        dct['lint_error']= int(request.POST.get('lint_error','0'))
        dct['judger']= request.POST.get('judger','LOCAL')
    if all([dct['problem_id'],dct['user_id'],dct['ip'],dct['code_length']]):   #all() 所有内容不为 0 、‘’、false
            insertRes=Solution.objects.create(**dct)
            solution_id = insertRes.solution_id
    else:
        return JsonResponse('stroeError', safe=False)
    det={'solution_id':solution_id,'source':code}
    SourceCodeUser.objects.create(**det)
    SourceCode.objects.create(**det)
    Solution.objects.filter(solution_id=solution_id).update(result=0)
    # 每完成1题积分为 ：题目难度等级*2分
    problem_id = insertRes.problem_id
    user_id = insertRes.user_id
    problem = Problem.objects.filter(problem_id=problem_id).first()
    solution = Solution.objects.filter(problem_id=problem_id, user_id=user_id).first()
    solution_count = Solution.objects.filter(problem_id=problem_id, user_id=user_id,result = 4).count()
    user = Users.objects.get(user_id = user_id)
    if int(solution.result) ==4 and solution_count == 1:
        user.score = problem.difficulty * 2
    return JsonResponse('stroePass', safe=False)


#重判题目
def rejudgeProblem(request):

    if request.method == 'POST':
        admin = request.POST.get('admin')
        if not (verifyPrivilege(admin)[0][0] == 1 or verifyPrivilege(admin)[0][0] == 0):
            massage = {'err': 'Insufficient authority'}
            return JsonResponse(massage, safe=False)
        rj_pid = request.POST.get('rj_pid','')
        rj_sid= request.POST.get('rj_sid','')
        rj_cid= request.POST.get('rj_cid','')

    if rj_pid is not None:
        reJudge(rj_pid)
        massage = {'message': ' yes'}
        return JsonResponse(massage, safe=False)
    elif rj_sid is not None:
        reJudge(rj_sid)
        massage = {'message': ' yes'}
        return JsonResponse(massage, safe=False)
    elif rj_cid is not None:
        reJudge(rj_cid)
        massage = {'message': ' yes'}
        return JsonResponse(massage, safe=False)

#获取当前用户最新ip
def getNewIp(request):
    if request.method == 'GET':
        ip = get_ip(request)

        return JsonResponse(ip, safe=False)

#导出竞赛日志
def contestLogs(request):
    if request.method == 'POST':
        admin = request.POST.get('admin')
        if not (verifyPrivilege(admin)[0][0] == 1 or verifyPrivilege(admin)[0][0] == 0 or JudgmentAuthority(admin, 'contest_creator')):
            massage = {'err': 'Insufficient authority'}
            return JsonResponse(massage, safe=False)
        contest_id = request.POST.get('contest_id')
        file=getLog(contest_id)

        return file

#防作弊接口
def contestSuspect(request):
    if request.method == 'POST':
        admin = request.POST.get('admin')
        if not (verifyPrivilege(admin)[0][0] == 1 or verifyPrivilege(admin)[0][0] == 0 or JudgmentAuthority(admin, 'contest_creator')):
            massage = {'err': 'Insufficient authority'}
            return JsonResponse(massage, safe=False)
        contest_id = request.POST.get('contest_id')
    solutions = Solution.objects.filter(contest_id=contest_id).all()
    uid_set = set()
    identical_ip_data = []
    different_uid_data = []
    for data in solutions:
        uid = data.user_id
        uid_set.add(uid)
    for data in uid_set:
        ip_set = set()
        ips = Solution.objects.filter(contest_id = contest_id,user_id = data).values('ip')
        for ip in ips:
            ip = ip['ip']
            ip_set.add(ip)
        if len(ip_set) > 1:
            id_set = set()
            for ip in ip_set:
                u_id = Solution.objects.filter(contest_id=contest_id, ip=ip).values('user_id')
                for id in u_id:
                    id = id['user_id']
                    id_set.add(id)
                count = len(id_set)
                identical_ip_data.append(
                    {
                        'user_id': data,
                        'ip': ip,
                        'count':count
                    }
                )

        for ip in ip_set:
            id_set = set()
            u_id = Solution.objects.filter(contest_id=contest_id, ip=ip).values('user_id')
            for id in u_id:
                id = id['user_id']
                id_set.add(id)
            count = len(id_set)
            if count>1:
                different_uid_data.append(
                    {
                        'user_id': data,
                        'ip': ip,
                        'count': count
                    }
                )
        different_uid_data = sorted(different_uid_data,key=lambda x:(-x['count'],x['ip']))
        identical_ip_data = sorted(identical_ip_data,key=lambda x:(x['user_id'],x['ip']))
    result = {'different_uid_data':different_uid_data,'identical_ip_data':identical_ip_data}
    return JsonResponse(result, safe=False)



#获取当前竞赛气球名单
def get_BalloonList(request):
    if request.method == 'GET':
        cid = request.GET.get('contest_id',None)
        page = int(request.GET.get('page',1))
        cid = cid.replace(" ","")
    if not cid:
        return JsonResponse({'err':'contest_id cannot be empty'}, safe=False)
    if cid.isdigit()!=True:
        return JsonResponse({'err':'contest_id input error'}, safe=False)
    problems=ContestProblem.objects.filter(contest_id=cid).values('problem_id')
    array1=[]
    for pro in problems:
        pro = pro['problem_id']
        array1.append(pro)
    array1.sort()
    proinfo={}
    i=0
    for pro in array1:
        i+=1
        proinfo[pro]=i
    contestinfo=Solution.objects.filter(contest_id=cid,result=4)
    for info in contestinfo:
        pan=Balloon.objects.filter(
            user_id=info.user_id,
            cid=cid,
            pid=info.problem_id
            )
        if pan.count()==0:
            balloon=Balloon(
               user_id=info.user_id,
               sid=proinfo[info.problem_id],
               cid=cid,
               pid=info.problem_id,
               status=1
               )
            balloon.save()
    s=['pink','red','orange','yellow','green','cyan','blue','black','white','grey',
       'violet','blackish green','tan','sky blue','amber','coffee','cream','rainbow',
       'silver','raisin','grape']
    balloonList = Balloon.objects.filter(cid=cid)
    massage=[]
    statu=['已发放','未发放']
    if balloonList.count() == 0:
        return JsonResponse({'err':'None'}, safe=False)
    total=len(balloonList)
    i=(page-1)*50
    balloonList=balloonList[(page-1)*50:page*50]
    for balloon in balloonList:
        i+=1
        list1={
            'number':i,
            'user_id':balloon.user_id,
            'color':s[balloon.sid],
            'problem_id':balloon.pid,
            'status':statu[ balloon.status ]
        }
        massage.append(list1)
    return JsonResponse({'massage':massage, 'total':total}, safe=False)


#打印未发送气球名单,清空未发放气球名单
def print_BalloonList(request):
    if request.method == 'GET':
        new_user=request.GET.get('new_user',None)
        cid = request.GET.get('contest_id',None)
        page = request.GET.get('page',1)
        if not (verifyPrivilege(new_user)[0][0] == 1 or verifyPrivilege(new_user)[0][0] == 0 or JudgmentAuthority(new_user, 'balloon & printer')):
            massage = {'err': 'Insufficient authority'}
            return JsonResponse(massage, safe=False)
    if new_user == '':
        return JsonResponse({'err':'You are not logged in. Please login and try again.'}, safe=False)
    if cid == '':
        return JsonResponse({'err':'contest_id cannot be empty'}, safe=False)
    if cid.isdigit()!=True:
        return JsonResponse({'err':'contest_id input error'}, safe=False)
    s=['pink','red','orange','yellow','green','cyan','blue','black','white','grey',
       'violet','blackish green','tan','sky blue','amber','coffee','cream','rainbow',
       'silver','raisin','grape']
    balloonList = Balloon.objects.filter(cid=cid)
    massage=[]
    a=int(page)*50
    a=min(balloonList.count(),a)
    b=(int(page)-1)*50
    b=max(b,0)
    num=0
    statu=['已发放','未发放']
    balloon=[]
    for i in range(b,a):
        if balloonList[i].status==1:
            num+=1
            list1={
                'number':num,
                'user_id':balloonList[i].user_id,
                'color':s[balloonList[i].sid],
                'problem_id':balloonList[i].pid,
                'status':statu[ balloonList[i].status ]
            }
            massage.append(list1)
        balloon.append(balloonList[i])
    for ball in balloon:
        ball.status=0
        ball.save()
    if (len(massage)==0):
        return JsonResponse({'err':'None'}, safe=False)
    total = len(massage)
    return JsonResponse({'massage':massage, 'total':total, 'information':'Sent successfully'}, safe=False)


#发送某一气球
def send_Balloon(request):
    if request.method == 'GET':
        new_user=request.GET.get('new_user',None)
        new_user=new_user.replace(" ","")
        cid = request.GET.get('contest_id',None)
        cid = cid.replace(" ","")
        user_id=request.GET.get('user_id',None)
        pid=request.GET.get('problem_id',None)
        if not (verifyPrivilege(new_user)[0][0] == 1 or verifyPrivilege(new_user)[0][0] == 0 or JudgmentAuthority(new_user, 'balloon & printer')):
            massage = {'err': 'Insufficient authority'}
            return JsonResponse(massage, safe=False)
    if new_user == '':
        return JsonResponse({'err':'You are not logged in. Please login and try again .'}, safe=False)

    if len(user_id.replace(" ","")) == 0:
        return JsonResponse({'err':'user_id cannot be empty'}, safe=False)
    if cid == '':
        return JsonResponse({'err':'contest_id cannot be empty'}, safe=False)
    if cid.isdigit()!=True:
        return JsonResponse({'err':'contest_id input error'}, safe=False)
    balloon = Balloon.objects.filter(cid=cid,user_id=user_id,pid=pid)
    if len(balloon)==0:
        return JsonResponse({'err':'None'}, safe=False)
    for ball in balloon:
        ball.status=0
        ball.save()
    return JsonResponse({'err':'Sent successfully'}, safe=False)


#查看题解内容
def getProblemSolution(request):
    if request.method == 'GET':
        topic_id = request.GET.get('topic_id', None)
        topic = Topic.objects.filter(topic_id =topic_id).first()
        topic_data =[]
        topic_data.append(
            {
                'title': topic.title.decode('utf-8'),
                'content': topic.content,
                'time': topic.time,
                'author_id': topic.author_id
            }
        )
        return JsonResponse(topic_data, safe=False)



# #积分系统
# def integralExchange(request):
#
#
#
#
#     #每周日晚上12点为基准，每周排名前3名得30分，前8名得20分，前15名的10分，取最高值，不重复记分
#     currentdate = datetime.date.today()
#     year = currentdate.year
#     month = currentdate.month
#     day = currentdate.day
#     currentday = calendar.weekday(year, month, day)
#     now = datetime.datetime.now()
#     if currentday ==6:
#         users =getRankListByTime(now - datetime.timedelta(days=7), 0, 16)
#         index=0
#         for data in users:
#             if index>8:
#                 user = data[0]
#                 userinfo = Users.objects.get(user_id=user)
#                 userinfo.score +=10
#             if index>3 and index<8 :
#                 user = data[0]
#                 userinfo = Users.objects.get(user_id=user)
#                 userinfo.score += 20
#             user = data[0]
#             userinfo = Users.objects.get(user_id=user)
#             userinfo.score += 30
#             index += 1
#
#     #每个月1月1日0点为基准，月排名前3得100分，前8名得60分，前15名得30分
#     if firstDayOfMonth(dtime.today()).day == dtime.today().day:
#         users = getRankListByTime(now - datetime.timedelta(days=30), 0, 16)
#         index = 0
#         for data in users:
#             if index > 8:
#                 user = data[0]
#                 userinfo = Users.objects.get(user_id=user)
#                 userinfo.score += 30
#             if index > 3 and index<8:
#                 user = data[0]
#                 userinfo = Users.objects.get(user_id=user)
#                 userinfo.score += 60
#             user = data[0]
#             userinfo = Users.objects.get(user_id=user)
#             userinfo.score += 100
#             index += 1
#
#     #连续7天登陆得10分，连续7天不登录扣20分
#     time_data = []
#     time = (datetime.datetime.now() - datetime.timedelta(days=7))
#     login = Loginlog.objects.filter(user_id =user_id, time__gt=time).all()
#     user = Users.objects.filter(user_id = user_id).first()
#     if not login:
#         user.score -= 20
#     else:
#         for data in login:
#             time_data.append(data.time)
#         f = 1
#         for data in time_data:
#             for i in range(7):
#                 time1 = (datetime.datetime.now() - datetime.timedelta(days=i))
#                 time3 = (datetime.datetime.now() - datetime.timedelta(days=i+2))
#                 if time1 <= data and data<=time3:
#                     f = 1
#                 else:
#                     f = 0
#                     break
#             if f == 0:
#                 break
#         if f == 1:
#             user.score += 10
#
#     #参加公开、私有比赛，第一名得100分、有效提交的前8%得50分，有效提交的前23%得30分，有效提交的前48%得10分，团队赛每个成员得相同分数，取最高值，不重复记分。
#     contest = Contest.objects.filter(contest_id = contest_id).first()
#     now = datetime.datetime.now()
#     if contest.end_time == now:
#         users = getUsers(contest_id)
#         user_count = len(users)
#         one_user = 1
#         two_user = user_count*0.08//1+1
#         three_user = user_count*0.23//1+1
#         four_user = user_count * 0.48 // 1 + 1
#         signs = Signup.objects.filter(contest_id=contest_id).all()
#         for data in signs:
#             user1 = Users.objects.get(user_id=data.user1).first()
#             user2 = Users.objects.get(user_id=data.user2).first()
#             user3 = Users.objects.get(user_id=data.user3).first()
#             if user1:
#                 rank1 = getUserContestRank(user1)
#             if user2:
#                 rank2 = getUserContestRank(user2)
#             if user3:
#                 rank3 = getUserContestRank(user3)
#             if rank1 and rank2 and rank3:
#                 rank = min(rank1,rank2,rank3)
#             elif rank1 and rank3:
#                 rank = min(rank1, rank2)
#             elif rank2 and rank3:
#                 rank = min(rank1, rank2)
#             elif rank1:
#                 rank = rank1
#             elif rank2:
#                 rank = rank2
#             elif rank3:
#                 rank = rank3
#             if rank == one_user:
#                 if user1:
#                     user1.score += 100
#                 if user2:
#                     user2.score += 100
#                 if user3:
#                     user3.score += 100
#             elif rank >= two_user:
#                 if user1:
#                     user1.score += 50
#                 if user2:
#                     user2.score += 50
#                 if user3:
#                     user3.score += 50
#             elif rank >= three_user:
#                 if user1:
#                     user1.score += 30
#                 if user2:
#                     user2.score += 30
#                 if user3:
#                     user3.score += 30
#             elif rank >= four_user:
#                 if user1:
#                     user1.score += 10
#                 if user2:
#                     user2.score += 10
#                 if user3:
#                     user3.score += 10
#             if user1:
#                 user.remove(user1)
#             if user2:
#                 user.remove(user2)
#             if user3:
#                 user.remove(user3)
#         for user in users:
#             user = Users.objects.get(user_id = user)
#             rank = getUserContestRank(user_id)
#             if rank == one_user:
#                 user.score += 100
#             elif rank >= two_user:
#                 user.score += 50
#             elif rank >= three_user:
#                 user.score += 30
#             elif rank >= four_user:
#                 user.score += 10


#解析xml 题库文件
def importXmlProblem(request):

    if request.method == 'POST':
        admin = request.POST.get('admin')
        if not (verifyPrivilege(admin)[0][0] == 1 or verifyPrivilege(admin)[0][0] == 0):
            massage = {'err': 'Insufficient authority'}
            return JsonResponse(massage, safe=False)
    filePath = open()
    DOMTree = parse(filePath)
    # 获取xml文档对象，就是拿到树的根
    collection = DOMTree.documentElement
    # 获取所有的子节点
    items = collection.getElementsByTagName('item')
    dct ={}
    for item in items:
        dct['title'] = item.getElementsByTagName('title')[0].data
        dct['time_limit'] = item.getElementsByTagName('time_limit')[0].data
        dct['memory_limit'] = item.getElementsByTagName('memory_limit')[0].data
        dct['description'] = item.getElementsByTagName('description')[0].data
        dct['input'] = item.getElementsByTagName('input')[0].data
        dct['output'] = item.getElementsByTagName('output')[0].data
        dct['sample_input'] = item.getElementsByTagName('sample_input')[0].data
        dct['sample_output'] = item.getElementsByTagName('sample_output')[0].data
        dct['title'] = item.getElementsByTagName('title')[0].data
        if(all(dct['title'], dct['time_limit'], dct['memory_limit'], dct['description'], dct['input'], dct['output'], dct['sample_input'], dct['sample_output'])):
            Problem.objects.create(**dct)

#导出竞赛题目
def exportContestProblem(request):
    if request.method == 'POST':
        admin = request.POST.get('admin')
        contest_id = request.POST.get('contest_id')
        if not (verifyPrivilege(admin)[0][0] == 1 or verifyPrivilege(admin)[0][0] == 0 or JudgmentAuthority(admin, 'contest_creator')):
            massage = {'err': 'Insufficient authority'}
            return JsonResponse(massage, safe=False)

        problems_id = ContestProblem.objects.filter(contest_id=contest_id).values('problem_id')
        doc = xml.dom.minidom.Document()
        root = doc.createElement('fps')
        doc.appendChild(root)
        for problem_ids in problems_id:

            problem_id = problem_ids['problem_id']
            problem = Problem.objects.filter(problem_id=str(problem_id)).first()
            # 给根节点添加一个叶子节点
            item = doc.createElement('item')
            # 叶子节点下再嵌套叶子节点 ---父节点
            title = doc.createElement('title')
            # 给节点添加文本节点
            title.appendChild(doc.createTextNode(str(problem.title)))
            time_limit = doc.createElement('time_limit')
            time_limit.setAttribute('unit', 'b')
            time_limit.appendChild(doc.createTextNode(str(problem.time_limit)))
            memory_limit = doc.createElement('memory_limit')
            memory_limit.setAttribute('unit', 'mb')
            memory_limit.appendChild(doc.createTextNode(str(problem.memory_limit)))
            description = doc.createElement('description')
            description.appendChild(doc.createTextNode(str(problem.description)))
            input = doc.createElement('input')
            input.appendChild(doc.createTextNode(str(problem.input)))
            output = doc.createElement('output')
            output.appendChild(doc.createTextNode(str(problem.output)))
            sample_input = doc.createElement('sample_input')
            sample_input.appendChild(doc.createTextNode(str(problem.sample_input)))
            sample_output = doc.createElement('sample_output')
            sample_output.appendChild(doc.createTextNode(str(problem.sample_output)))
            hint = doc.createElement('hint')
            hint.appendChild(doc.createTextNode(str(problem.hint)))
            source = doc.createElement('source')
            source.appendChild(doc.createTextNode(str(problem.source)))
            # 将各叶子节点添加到父节点中
            item.appendChild(title)
            item.appendChild(time_limit)
            item.appendChild(memory_limit)
            item.appendChild(description)
            item.appendChild(input)
            item.appendChild(output)
            item.appendChild(sample_input)
            item.appendChild(sample_output)
            item.appendChild(hint)
            item.appendChild(source)
            # 将company节点添加到根节点中
            root.appendChild(item)

        # 此处需要用codecs.open可以指定编码方式
        fp = open(r'..//..//judge//data//problem.xml', 'w', encoding='utf-8')
        # 将内存中的xml写入到文件
        doc.writexml(fp, indent='', addindent='\t', newl='\n', encoding='utf-8')
        fp.close()
        response = FileResponse(open('..//..//judge//data//problem.xml', 'rb'))
        response['content_type'] = "application/octet-stream"
        response['Content-Disposition'] = 'attachment; filename=contestLogs'
        return response



















